Class: Karta::MapperRegistry
- Inherits:
-
Object
- Object
- Karta::MapperRegistry
- Defined in:
- lib/karta/mapper_registry.rb
Overview
Simple collection class for mappers
Instance Attribute Summary collapse
-
#mappers ⇒ Object
readonly
Returns the value of attribute mappers.
Instance Method Summary collapse
-
#find(from_klass:, to_klass:) ⇒ Karta::Mapper
Find a mapper in the registry.
-
#initialize ⇒ MapperRegistry
constructor
A new instance of MapperRegistry.
-
#register(mapper:, from_klass: nil, to_klass: nil) ⇒ MapperRegistry
Register a mapper to the registry.
Constructor Details
#initialize ⇒ MapperRegistry
Returns a new instance of MapperRegistry.
7 8 9 |
# File 'lib/karta/mapper_registry.rb', line 7 def initialize @mappers = [] end |
Instance Attribute Details
#mappers ⇒ Object (readonly)
Returns the value of attribute mappers.
5 6 7 |
# File 'lib/karta/mapper_registry.rb', line 5 def mappers @mappers end |
Instance Method Details
#find(from_klass:, to_klass:) ⇒ Karta::Mapper
Find a mapper in the registry
49 50 51 52 53 54 55 |
# File 'lib/karta/mapper_registry.rb', line 49 def find(from_klass:, to_klass:) mappers.find(lambda do raise MapperNotFoundError.new(from_klass, to_klass) end) do |mapper| mapper[:from_klass] == from_klass && mapper[:to_klass] == to_klass end.fetch(:mapper) end |
#register(mapper:, from_klass: nil, to_klass: nil) ⇒ MapperRegistry
Register a mapper to the registry.
If no from_klass or to_klass are specified it will try to parse this from the class name of the mapper. This assumes that the class name of the mapper is on the form ‘[from class]To[to class]Mapper`, e.g. `FooToBarMapper`. For obvious reasons this makes it hard to handle cases where one of the classes is namespaced, e.g. `Baz::Bar`. For those cases the `from_klass` and `to_klass` must be specified.
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/karta/mapper_registry.rb', line 29 def register(mapper:, from_klass: nil, to_klass: nil) unless from_klass && to_klass from_klass, to_klass = *klasses_from_class_name(mapper.to_s) end mappers.push(mapper: mapper, from_klass: from_klass, to_klass: to_klass) self end |