Class: Wepo::Mapper
- Inherits:
-
Object
- Object
- Wepo::Mapper
- Defined in:
- lib/wepo/mapper.rb
Instance Method Summary collapse
-
#initialize(entity_class:, model_class:) ⇒ Mapper
constructor
A new instance of Mapper.
- #map_entity(entity) ⇒ Object
- #map_model(model) ⇒ Object
Constructor Details
#initialize(entity_class:, model_class:) ⇒ Mapper
Returns a new instance of Mapper.
4 5 6 7 |
# File 'lib/wepo/mapper.rb', line 4 def initialize(entity_class:, model_class:) @entity_class = entity_class @model_class = model_class end |
Instance Method Details
#map_entity(entity) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/wepo/mapper.rb', line 27 def map_entity(entity) model = @model_class.find_or_initialize_by(id: entity.id) model.attributes.keys.each do |name| if name.include?('_id') association = name.gsub(/_id/,'').to_sym entity_association = entity.send(association) model.send(setter(name), entity.send(association).id) if entity_association else model.send(setter(name), entity.send(name)) if entity.respond_to?(name) end end model end |
#map_model(model) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/wepo/mapper.rb', line 9 def map_model(model) entity = @entity_class.new entity.attributes.keys.each do |name| value = model.send(name) if value.respond_to? :each values = value.map do |v| entity_class = (v.class.name + "Entity").constantize mapper = Mapper.new(entity_class: entity_class, model_class: v.class) mapper.map_model(v) end entity.send(setter(name), values) else entity.send(setter(name), value) end end entity end |