Class: Karta::MapperRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/karta/mapper_registry.rb

Overview

Simple collection class for mappers

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMapperRegistry

Returns a new instance of MapperRegistry.



7
8
9
# File 'lib/karta/mapper_registry.rb', line 7

def initialize
  @mappers = []
end

Instance Attribute Details

#mappersObject (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

Parameters:

  • from_klass (Class)

    the class the mapper is supposed to map from

  • to_klass (Class)

    the class the mapper is supposed to map to

Returns:

Raises:



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.

Parameters:

  • mapper (Karta::Mapper)

    the mapper to register

  • from_klass (Class) (defaults to: nil)

    the class the mapper is supposed to map from

  • to_klass (Class) (defaults to: nil)

    the class the mapper is supposed to map to

Returns:

  • (MapperRegistry)

    the mapper registry after the mapper has been added

Raises:

  • (InvalidNameError)

    if no ‘from_klass` or `to_klass` is specified and the class name of the mapper does not follow the correct format.



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