Class: Mapping::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/mapping/model.rb

Direct Known Subclasses

ObjectModel

Constant Summary collapse

PREFIX =
'map_'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.map(klass, &block) ⇒ Object

Add a mapping from a given input class to a specific block.



36
37
38
39
# File 'lib/mapping/model.rb', line 36

def self.map(klass, &block)
  method_name = self.method_for_mapping(klass)
  define_method(method_name, &block)
end

.map_identity(*klasses) ⇒ Object

Sometimes you just want to map things to themselves (the identity function). This makes it convenient to specify a lot of identity mappings.



42
43
44
45
46
# File 'lib/mapping/model.rb', line 42

def self.map_identity(*klasses)
  klasses.each do |klass|
    self.map(klass) {|value| value}
  end
end

.method_for_mapping(klass) ⇒ Object

This function generates mapping names like ‘map_Array` and `map_Hash` which while a bit non-standard are perfectly fine for our purposes and this never really needs to leak.



26
27
28
# File 'lib/mapping/model.rb', line 26

def self.method_for_mapping(klass)
  PREFIX + klass.name.gsub(/::/, '_')
end

.unmap(klass) ⇒ Object

Remove a mapping, usually an inherited one, which you don’t want.



49
50
51
52
# File 'lib/mapping/model.rb', line 49

def self.unmap(klass)
  method_name = self.method_for_mapping(klass)
  undef_method(method_name)
end

Instance Method Details

#map(root, *args) ⇒ Object

The primary function, which maps an input object to an output object.



55
56
57
58
59
# File 'lib/mapping/model.rb', line 55

def map(root, *args)
  method_name = self.method_for_mapping(root)
  
  self.send(method_name, root, *args)
end

#method_for_mapping(object) ⇒ Object

Get the name of the method for mapping the given object.



31
32
33
# File 'lib/mapping/model.rb', line 31

def method_for_mapping(object)
  self.class.method_for_mapping(object.class)
end