Module: Zippo::BinaryStructure::Base

Defined in:
lib/zippo/binary_structure/base.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.after_structure_definition(&block) ⇒ Object



72
73
74
75
# File 'lib/zippo/binary_structure/base.rb', line 72

def after_structure_definition(&block)
  @hooks ||= []
  @hooks << block
end

.after_structure_definition_hooks_for(klass) ⇒ Object



66
67
68
69
70
# File 'lib/zippo/binary_structure/base.rb', line 66

def after_structure_definition_hooks_for(klass)
  @hooks.each do |hook|
    hook.call(klass)
  end if @hooks
end

Instance Method Details

#binary_structure(&block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/zippo/binary_structure/base.rb', line 35

def binary_structure(&block)
  @structure = Structure.create(self, &block)
  const_set :Packer, Class.new(BinaryPacker)
  self::Packer.structure = @structure
  const_set :Unpacker, Class.new(BinaryUnpacker)
  self::Unpacker.structure = @structure

  @structure.fields.each do |field|
    attr_reader field.name
    if @structure.dependent? field.name
      define_method "#{field.name}=" do |_value|
        fail "can't mutate a dependent field"
      end
    else
      if field.dependent
        class_eval """
          def #{field.name}= value
            @#{field.dependent} = value.bytesize
            @#{field.name} = value
          end
        """
      else
        attr_writer field.name
      end
    end
  end
  include InstanceMethods
  extend ClassMethods
  Base.after_structure_definition_hooks_for(self)
end