Method: BitFields#field

Defined in:
lib/bit_fields.rb

#field(name, unpack_recipe = 'C', &bit_fields_definitions_block) ⇒ Object

Defines a field to be extracted with String#unpack from the raw value

name

the name of the field (that will be used to access it)

unpack_recipe

the String#unpack directive corresponding to this field (optional, defaults to char: “C”)

bit_fields_definitions_block

the block in which bit_fields can be defined (optional)

Also defines the attribute reader method

TODO: add a skip bits syntax



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/bit_fields.rb', line 91

def field name, unpack_recipe = 'C', &bit_fields_definitions_block
  include InstanceMethods # when used we include instance methods
  
  # Setup class "instance" vars
  @fields        ||= []
  @bit_fields    ||= {}
  @unpack_recipe ||= ""
  
  # Register the field definition
  @unpack_recipe << unpack_recipe
  @fields        << name
  
  # Define the attribute accessor
  bits_attr_accessor(name)
  
  # There's a bit-structure too?
  if block_given?
    @_current_bit_fields = []
    
    bit_fields_definitions_block.call
    
    @bit_fields[name] = @_current_bit_fields
    @_current_bit_fields = nil
  end
end