Class: Depict::Mapping

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Mapping

Returns a new instance of Mapping.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/depict/mapping.rb', line 14

def initialize(name, options={})
   @name = name.to_sym

   @target_name = options.fetch(:as, @name)

   @converter = options[:with]

   @serializer = options[:serialize_with]

   @deserializer = options[:deserialize_with]
end

Instance Attribute Details

#converterObject (readonly)

Returns the value of attribute converter.



8
9
10
# File 'lib/depict/mapping.rb', line 8

def converter
  @converter
end

#deserializerObject (readonly)

Returns the value of attribute deserializer.



12
13
14
# File 'lib/depict/mapping.rb', line 12

def deserializer
  @deserializer
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/depict/mapping.rb', line 4

def name
  @name
end

#serializerObject (readonly)

Returns the value of attribute serializer.



10
11
12
# File 'lib/depict/mapping.rb', line 10

def serializer
  @serializer
end

#target_nameObject (readonly)

Returns the value of attribute target_name.



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

def target_name
  @target_name
end

Instance Method Details

#deserialize(object, attributes) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/depict/mapping.rb', line 40

def deserialize(object, attributes)
   value = attributes[target_name]

   if deserializer
      object.send("#{name}=", deserializer.call(value))
   elsif converter
      object.send("#{name}=", converter.deserialize(value))
   else
      object.send("#{name}=", value)
   end

   nil
end

#serialize(object, attributes) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/depict/mapping.rb', line 26

def serialize(object, attributes)
   value = object.send(name)
   
   if serializer
      attributes[target_name] = serializer.call(value)
   elsif converter
      attributes[target_name] = converter.serialize(value)
   else
      attributes[target_name] = value
   end

   nil
end