Module: StructPacking::Base::ClassMethods

Defined in:
lib/struct_packing/base.rb

Overview

Common extending methods for Packable and Unpackable.

Automatically extend on including StructPacking::Base module.

Instance Method Summary collapse

Instance Method Details

#attr_mapped_structObject

Declare this struct as accessible by attr-style-access(access by name= operator). This is default behavior.



139
140
141
142
# File 'lib/struct_packing/base.rb', line 139

def attr_mapped_struct
  set_field_getter {|obj, name| obj.send(name) }
  set_field_setter {|obj, name, value| obj.send("#{name}=", value) }
end

#byte_format=(text) ⇒ Object Also known as: define_struct

Set structure format for this class by string.



85
86
87
88
89
# File 'lib/struct_packing/base.rb', line 85

def byte_format=(text)
  @struct_internal_format = text

  true
end

#get_field_value(obj, name) ⇒ Object

Call getter procedure to get field of target object.



105
106
107
108
109
110
111
# File 'lib/struct_packing/base.rb', line 105

def get_field_value(obj, name)
  begin
    @struct_field_getter.call(obj, name)
  rescue
    0
  end
end

#hash_mapped_structObject

Declare this struct as accessible by hash-style-access(access by [] operator).



132
133
134
135
# File 'lib/struct_packing/base.rb', line 132

def hash_mapped_struct
  set_field_getter {|obj, name| obj[name.to_sym] }
  set_field_setter {|obj, name, value| obj[name.to_sym] = value }
end

#pack_templateObject

Get Ruby’s pack template string for this class.



94
95
96
97
98
99
100
101
102
# File 'lib/struct_packing/base.rb', line 94

def pack_template
  if self.to_s =~ /^.*<(.*):0x.*/
    clsname = $1
  else
    clsname = self.to_s
  end
  
  Util.pack_template_from( @struct_internal_format, clsname )
end

#set_field_getter(&block) ⇒ Object

Set gettter procedure.



122
123
124
# File 'lib/struct_packing/base.rb', line 122

def set_field_getter(&block)
  @struct_field_getter = block
end

#set_field_setter(&block) ⇒ Object

Set settter procedure.



127
128
129
# File 'lib/struct_packing/base.rb', line 127

def set_field_setter(&block)
  @struct_field_setter = block
end

#set_field_value(obj, name, value) ⇒ Object

Call setter procedure to set value to the field of target object.



114
115
116
117
118
119
# File 'lib/struct_packing/base.rb', line 114

def set_field_value(obj, name, value)
  begin
    @struct_field_setter.call(obj, name, value)
  rescue
  end
end