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(*klasses, &block) ⇒ Object

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



21
22
23
24
25
26
# File 'lib/mapping/model.rb', line 21

def self.map(*klasses, &block)
	klasses.each do |klass|
		method_name = self.method_for_mapping(klass)
		define_method(method_name, &block)
	end
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.



29
30
31
# File 'lib/mapping/model.rb', line 29

def self.map_identity(*klasses)
	self.map(*klasses) {|value| value}
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.



11
12
13
# File 'lib/mapping/model.rb', line 11

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

.unmap(*klasses) ⇒ Object

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



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

def self.unmap(*klasses)
	klasses.each do |klass|
		method_name = self.method_for_mapping(klass)
		undef_method(method_name)
	end
end

Instance Method Details

#map(root, *arguments, **options) ⇒ Object

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



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

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

#method_for_mapping(object) ⇒ Object

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



16
17
18
# File 'lib/mapping/model.rb', line 16

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