Class: Reform::Composition
- Inherits:
-
Object
- Object
- Reform::Composition
- Defined in:
- lib/reform/composition.rb
Overview
Keeps composition of models and knows how to transform a plain hash into a nested hash.
Class Method Summary collapse
- .map(options) ⇒ Object
-
.map_from(representer) ⇒ Object
Specific to representable.
- .model_for_property(name) ⇒ Object
Instance Method Summary collapse
-
#initialize(models) ⇒ Composition
constructor
A new instance of Composition.
-
#nested_hash_for(attrs) ⇒ Object
TODO: make class method?.
Constructor Details
#initialize(models) ⇒ Composition
Returns a new instance of Composition.
49 50 51 52 53 |
# File 'lib/reform/composition.rb', line 49 def initialize(models) models.each do |name, obj| instance_variable_set(:"@#{name}", obj) end end |
Class Method Details
.map(options) ⇒ Object
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/reform/composition.rb', line 5 def map() @attr2obj = {} # {song: ["title", "track"], artist: ["name"]} .each do |mdl, meths| create_accessors(mdl, meths) attr_reader mdl meths.each { |m| @attr2obj[m.to_s] = mdl } end end |
.map_from(representer) ⇒ Object
Specific to representable.
17 18 19 20 21 22 23 24 25 |
# File 'lib/reform/composition.rb', line 17 def map_from(representer) = {} representer.representable_attrs.each do |cfg| [cfg.[:on]] ||= [] [cfg.[:on]] << cfg.name end map end |
.model_for_property(name) ⇒ Object
27 28 29 |
# File 'lib/reform/composition.rb', line 27 def model_for_property(name) @attr2obj.fetch(name.to_s) end |
Instance Method Details
#nested_hash_for(attrs) ⇒ Object
TODO: make class method?
39 40 41 42 43 44 45 46 47 |
# File 'lib/reform/composition.rb', line 39 def nested_hash_for(attrs) {}.tap do |hsh| attrs.each do |name, val| obj = self.class.model_for_property(name) hsh[obj] ||= {} hsh[obj][name.to_sym] = val end end end |