Class: SuperMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/super_mapper.rb,
lib/super_mapper/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
'0.3.0'

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ SuperMapper

Returns a new instance of SuperMapper.

Yields:

  • (_self)

Yield Parameters:

  • _self (SuperMapper)

    the object that the method was called on



6
7
8
# File 'lib/super_mapper.rb', line 6

def initialize
  yield self if block_given?
end

Instance Method Details

#define_mapping(source_class, target_class, &block) ⇒ Object

Define a new mapping schema from a source class, mapping getters to setters

Parameters:

  • source_class (Class)

    the class that will act as the source for this mapping definition



14
15
16
# File 'lib/super_mapper.rb', line 14

def define_mapping source_class, target_class, &block
  mapping_registry["#{source_class}-#{target_class}"] = block
end

#map(source, target) ⇒ Object

Maps a source object to a target object using previously registered mappings

Parameters:

  • source (Object)

    the source object

  • target (Object | Class)

    the target object or class. If a class is given, it should have a no-args constructor since the new instance will be created calling target.new

Returns:

  • (Object)

    the target object, or a new instance of the target class, filled with values coming from the source

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
# File 'lib/super_mapper.rb', line 24

def map source, target
  return if source.nil?

  raise ArgumentError, 'target cannot be nil' if target.nil?
  
  target.is_a?(Class) ? map_object(source, target.new) : map_object(source, target)
end