class NWN::Resources::ContentObject

This is a generic index to a resource.

Attributes

io[RW]
offset[RW]
res_type[RW]
resref[RW]
size_override[RW]

Public Class Methods

new(resref, res_type, io = nil, offset = nil, size = nil) click to toggle source
# File lib/nwn/res.rb, line 25
def initialize resref, res_type, io = nil, offset = nil, size = nil
  @resref, @res_type = resref.downcase, res_type
  @io, @offset = io, offset
  @size_override = size

  raise ArgumentError, "Invalid object passed: responds_to :read, want @offset, but does not respond_to :seek" if
    @io.respond_to?(:read) && @offset && @offset != 0 && !@io.respond_to?(:seek)
end
new_from(filename, io = nil) click to toggle source

Create a new index to filename, optionally specifying io.

# File lib/nwn/res.rb, line 13
def self.new_from filename, io = nil
  FileTest.exists?(filename) or raise Errno::ENOENT unless io

  filename = File.expand_path(filename)
  base = File.basename(filename).split(".")[0..-2].join(".").downcase
  ext = File.extname(filename)[1..-1].downcase rescue ""
  res_type = NWN::Resources::Extensions[ext] or raise ArgumentError,
    "Not a valid extension: #{ext.inspect} (while packing #{filename})"

  ContentObject.new(base, res_type, io || filename, 0, io ? io.size : File.stat(filename).size)
end

Public Instance Methods

extension() click to toggle source

Get the extension of this object.

# File lib/nwn/res.rb, line 57
def extension
  @extension ||= NWN::Resources::Extensions.key(@res_type)
end
filename() click to toggle source

Get the canonical filename of this object.

# File lib/nwn/res.rb, line 52
def filename
  @filename ||= (@resref + "." + (self.extension || "unknown-#{@res_type}"))
end
get() click to toggle source

Get the contents of this object. This is a costly operation, loading the whole buffer. If you want fine-grained access, use ContentObject#io and do it yourself, observing ContentObject#offset and ContentObject#size.

# File lib/nwn/res.rb, line 42
def get
  if @io.respond_to?(:read)
    @io.seek(@offset ? @offset : 0)
    @io.e_read(self.size, "filename = #{filename}")
  else
    IO.read(@io)
  end
end
size() click to toggle source

Get the size in bytes of this object.

# File lib/nwn/res.rb, line 35
def size
  @size ||= (@size_override || (@io.is_a?(IO) ? @io.stat.size : File.stat(@io).size))
end