lib/bindata/base.rb in bindata-1.4.5 vs lib/bindata/base.rb in bindata-1.5.0

- old
+ new

@@ -80,10 +80,13 @@ end # Register all subclasses of this class. register_subclasses + # The registered name may be provided explicitly. + optional_parameter :name + # Creates a new data object. # # Args are optional, but if present, must be in the following order. # # +value+ is a value that is +assign+ed immediately after initialization. @@ -91,16 +94,31 @@ # +parameters+ is a hash containing symbol keys. Some parameters may # reference callable objects (methods or procs). # # +parent+ is the parent data object (e.g. struct, array, choice) this # object resides under. + # + # == Parameters + # + # Parameters may be provided at initialisation to control the behaviour of + # an object. These params are: + # + # <tt>:name</tt>:: The name that this object can be referred to may be + # set explicitly. This is only useful when dynamically + # generating types. + # <code><pre> + # BinData::Struct.new(:name => :my_struct, :fields => ...) + # array = BinData::Array.new(:type => :my_struct) + # </pre></code> + # def initialize(*args) value, parameters, parent = extract_args(args) @params = SanitizedParameters.sanitize(parameters, self.class) @parent = parent + register_prototype add_methods_for_check_or_adjust_offset initialize_shared_instance initialize_instance assign(value) if value @@ -109,11 +127,11 @@ attr_accessor :parent protected :parent= # Creates a new data object based on this instance. # - # All parameters will be be duplicated. Use this method + # All parameters will be be duplicated. Use this method # when creating multiple objects with the same parameters. def new(value = nil, parent = nil) obj = clone obj.parent = parent if parent obj.initialize_instance @@ -263,16 +281,30 @@ def extract_args(the_args) self.class.arg_extractor.extract(self.class, the_args) end + def register_prototype + if has_parameter?(:name) + RegisteredClasses.register(get_parameter(:name), self) + end + end + def furthest_ancestor if parent.nil? self else an = parent an = an.parent while an.parent an + end + end + + def binary_string(str) + if str.respond_to?(:force_encoding) + str.dup.force_encoding(Encoding::BINARY) + else + str.dup end end ########################################################################### # To be implemented by subclasses