Class: Rmodel::BaseMapper
- Inherits:
-
Object
- Object
- Rmodel::BaseMapper
show all
- Defined in:
- lib/rmodel/base_mapper.rb
Instance Method Summary
collapse
Constructor Details
#initialize(model) ⇒ BaseMapper
Returns a new instance of BaseMapper.
3
4
5
6
7
8
|
# File 'lib/rmodel/base_mapper.rb', line 3
def initialize(model)
@model = model
self.primary_key = :id
self.key_op = :to_sym
@attributes = {}
end
|
Instance Method Details
#define_attribute(attr, mapper = DummyMapper.instance) ⇒ Object
10
11
12
13
|
# File 'lib/rmodel/base_mapper.rb', line 10
def define_attribute(attr, mapper = DummyMapper.instance)
@attributes[attr] = mapper
self
end
|
#define_attributes(*attributes) ⇒ Object
15
16
17
18
|
# File 'lib/rmodel/base_mapper.rb', line 15
def define_attributes(*attributes)
attributes.each { |attr| define_attribute(attr) }
self
end
|
#define_timestamps ⇒ Object
20
21
22
|
# File 'lib/rmodel/base_mapper.rb', line 20
def define_timestamps
define_attributes :created_at, :updated_at
end
|
#deserialize(hash) ⇒ Object
24
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/rmodel/base_mapper.rb', line 24
def deserialize(hash)
return nil if hash.nil?
uni_hash = UniHash.new(hash, key_op)
object = @model.new
object.id = uni_hash[primary_key] if object.respond_to?(:id)
@attributes.each do |attr, mapper|
deserialized = mapper.deserialize(uni_hash[attr])
object.public_send "#{attr}=", deserialized
end
object
end
|
#serialize(object, id_included) ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/rmodel/base_mapper.rb', line 38
def serialize(object, id_included)
return nil if object.nil?
uni_hash = UniHash.new({}, key_op)
@attributes.each do |attr, mapper|
serialized = mapper.serialize(object.public_send(attr), id_included)
uni_hash[attr] = serialized
end
if id_included && object.respond_to?(:id)
uni_hash[primary_key] = object.id
end
uni_hash.to_hash
end
|