Class: Karta::Mapper
- Inherits:
-
Object
- Object
- Karta::Mapper
- Defined in:
- lib/karta/mapper.rb
Overview
Contains the basic functionality for a mapper object, the class is meant to be inherited by a mapper class in order to get the ‘#map method as well as being able to specify one-to-one mappings
Class Method Summary collapse
-
.map(from:, to:) ⇒ Object
Instantiates a mapper and runs the ‘#map` method.
-
.map!(from:, to:) ⇒ Object
Instantiates a mapper and runs the ‘#map!` method.
-
.mapping_methods ⇒ Array<Symbol>
Find all mapping methods defined on the mapper.
-
.one_to_one_mapping(attr, ...) ⇒ Object
Defines a one-to-one mapping on the mapper as a method.
Instance Method Summary collapse
-
#map(from:, to:) ⇒ Object
Maps an object to another using all mapping methods defined on the mapper.
-
#map!(from:, to:) ⇒ Object
Maps an object to another using all mapping methods defined on the mapper.
Class Method Details
.map(from:, to:) ⇒ Object
Instantiates a mapper and runs the ‘#map` method
63 64 65 |
# File 'lib/karta/mapper.rb', line 63 def self.map(from:, to:) new.map(from: from, to: to) end |
.map!(from:, to:) ⇒ Object
Instantiates a mapper and runs the ‘#map!` method
73 74 75 |
# File 'lib/karta/mapper.rb', line 73 def self.map!(from:, to:) new.map!(from: from, to: to) end |
.mapping_methods ⇒ Array<Symbol>
Find all mapping methods defined on the mapper.
38 39 40 |
# File 'lib/karta/mapper.rb', line 38 def self.mapping_methods public_instance_methods(true).grep(/^map_/) end |
.one_to_one_mapping(attr, ...) ⇒ Object
Defines a one-to-one mapping on the mapper as a method.
A one-to-one-mapping is a mapping where the attribute names are equal and no transformation is supposed to take place. E.g. ‘foo.id = bar.id`.
49 50 51 52 53 54 55 |
# File 'lib/karta/mapper.rb', line 49 def self.one_to_one_mapping(*attrs) attrs.each do |attr| define_method("map_#{attr}") do |from, to| to.send("#{attr}=", from.send(attr)) end end end |
Instance Method Details
#map(from:, to:) ⇒ Object
Maps an object to another using all mapping methods defined on the mapper. Mapping methods are defined as “one-to-one mappings” by using ‘.one_to_one_mapping`or by defining methods with names starting with ’map_’. The mapping methods are supposed to take the object which it is mapping from as well as the object which it should map into.
18 19 20 21 |
# File 'lib/karta/mapper.rb', line 18 def map(from:, to:) to_klass = to.is_a?(Class) ? to : to.class _map(from, to_klass.new) end |
#map!(from:, to:) ⇒ Object
Maps an object to another using all mapping methods defined on the mapper. see #map
30 31 32 33 |
# File 'lib/karta/mapper.rb', line 30 def map!(from:, to:) to = to.new if to.is_a?(Class) _map(from, to) end |