Module: Icss::ReceiverModel::ActsAsTuple::ClassMethods

Included in:
ClassMethods
Defined in:
lib/icss/receiver_model/acts_as_tuple.rb

Instance Method Summary collapse

Instance Method Details

#consume_tuple(tuple) ⇒ Object

walks through the tuple, destructively consuming each value in a depth-first walk of the field tree:

class Address < Icss::Thing
  field(:housenum, Integer)
  field(:street, String)
end
class Person <  Icss::Thing
  field(:full_name, String)
  field(:street_address, Address)
end
Person.consume_tuple(1214, 'W 6th St', 'Joe the Chimp')
# => #<Person street_address=#<Address housenum=1214, street='W 6th St'>, fullname='Joe the Chimp'>


83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/icss/receiver_model/acts_as_tuple.rb', line 83

def consume_tuple(tuple)
  obj = self.new
  fields.each do |field|
    if field[:type].respond_to?(:consume_tuple)
      val = field[:type].consume_tuple(tuple)
    else
      val = tuple.shift
    end
    obj.send("receive_#{field[:name]}", val) if val
  end
  obj.send(:run_after_receivers, {})
  obj
end

#tuple_fields(max_key_segments = 3) ⇒ Object

returns a depth-first traversal of the object’s fields, as RecordFields:

class Address < Icss::Thing
  field(:housenum, Integer)
  field(:street, String)
end
class Person <  Icss::Thing
  field(:full_name, String)
  field(:street_address, Address)
end
Person.tuple_keys
# => [ [<RecordField name='fullname' ...>],
#      [<RecordField name='street_address' ...>, <RecordField name='housenum' ...>],
#      [<RecordField name='street_address' ...>, <RecordField name='street' ...>],

Note that RecordField helpfully supplies a ‘parent’ attribute pointing to it parent record.

Parameters:

  • max_key_segments (Integer) (defaults to: 3)

    the maximum length of key (depth to recurse); a stark 3 by default.



58
59
60
61
62
63
64
65
66
67
# File 'lib/icss/receiver_model/acts_as_tuple.rb', line 58

def tuple_fields(max_key_segments=3)
  # return @tuple_fields if @tuple_fields
  @tuple_fields = field_schemas.flat_map do |fn, fld|
    if (max_key_segments > 1) && fld[:type].respond_to?(:tuple_fields)
      fld[:type].tuple_fields(max_key_segments-1).map{|subfield| [fld, subfield].flatten }
    else
      [[fld]]
    end
  end
end

#tuple_keys(max_key_segments = 3) ⇒ Object

returns a depth-first traversal of the object’s fields’ keys, as Strings:

class Address < Icss::Thing
  field(:housenum, Integer)
  field(:street, String)
end
class Person <  Icss::Thing
  field(:full_name, String)
  field(:street_address, Address)
end
Person.tuple_keys
# => ['fullname', 'street_address.housenum', 'street_address.street']

Parameters:

  • max_key_segments (Integer) (defaults to: 3)

    the maximum length of key (depth to recurse); a stark 3 by default.



34
35
36
# File 'lib/icss/receiver_model/acts_as_tuple.rb', line 34

def tuple_keys(max_key_segments=3)
  tuple_fields(max_key_segments).map{|field_set| field_set.map(&:name).join('.') }
end