Class NWN::Resources::ContentObject

  1. lib/nwn/res.rb
Parent: Object

This is a generic index to a resource.

Methods

public class

  1. new
  2. new_from

public instance

  1. extension
  2. filename
  3. get
  4. size

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)
[show 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)

Create a new index to filename, optionally specifying io.

[show source]
# 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 ()

Get the extension of this object.

[show source]
# File lib/nwn/res.rb, line 57
      def extension
        NWN::Resources::Extensions.index(@res_type)
      end
filename ()

Get the canonical filename of this object.

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

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.

[show source]
# 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 ()

Get the size in bytes of this object.

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