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.



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

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.



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

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.



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

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.



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

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, *args) ⇒ Object

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



57
58
59
60
61
# File 'lib/mapping/model.rb', line 57

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