Class: Kaitai::Struct::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/kaitai/struct/struct.rb

Overview

Common base class for all structured generated by Kaitai Struct. Stores stream object that this object was parsed from in #_io, stores reference to parent structure in #_parent and root structure in #_root and provides a few helper methods.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_io, _parent = nil, _root = self) ⇒ Struct

Returns a new instance of Struct.



15
16
17
18
19
# File 'lib/kaitai/struct/struct.rb', line 15

def initialize(_io, _parent = nil, _root = self)
  @_io = _io
  @_parent = _parent
  @_root = _root
end

Instance Attribute Details

#_ioObject (readonly)

Returns the value of attribute _io.



58
59
60
# File 'lib/kaitai/struct/struct.rb', line 58

def _io
  @_io
end

#_parentObject (readonly)

Returns the value of attribute _parent.



58
59
60
# File 'lib/kaitai/struct/struct.rb', line 58

def _parent
  @_parent
end

#_rootObject (readonly)

Returns the value of attribute _root.



58
59
60
# File 'lib/kaitai/struct/struct.rb', line 58

def _root
  @_root
end

Class Method Details

.from_file(filename) ⇒ Object

Factory method to instantiate a Kaitai Struct-powered structure, parsing it from a local file with a given filename.

Parameters:

  • filename (String)

    local file to parse



25
26
27
# File 'lib/kaitai/struct/struct.rb', line 25

def self.from_file(filename)
  self.new(Stream.open(filename))
end

Instance Method Details

#inspectObject

Implementation of Object#inspect to aid debugging (at the very least, to aid exception raising) for KS-based classes. This one uses a bit terser syntax than Ruby’s default one, purposely skips any internal fields (i.e. starting with ‘_`, such as `_io`, `_parent` and `_root`) to reduce confusion, and does no recursivity tracking (as proper general-purpose `inspect` implementation should do) because there are no endless recursion in KS-based classes by design (except for already mentioned internal navigation variables).



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/kaitai/struct/struct.rb', line 39

def inspect
  vars = []
  instance_variables.each { |nsym|
    nstr = nsym.to_s

    # skip all internal variables
    next if nstr[0..1] == '@_'

    # strip mandatory `@` at the beginning of the name for brevity
    nstr = nstr[1..-1]

    nvalue = instance_variable_get(nsym).inspect

    vars << "#{nstr}=#{nvalue}"
  }

  "#{self.class}(#{vars.join(' ')})"
end