Class: Jsoning::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/jsoning/foundations/mapper.rb

Overview

takes care of translating/fetching values from the object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMapper

Returns a new instance of Mapper.



12
13
14
15
16
# File 'lib/jsoning/foundations/mapper.rb', line 12

def initialize
  self.parallel_variable = nil
  self.default_value = nil
  self.nullable = true
end

Instance Attribute Details

#custom_blockObject

Returns the value of attribute custom_block.



10
11
12
# File 'lib/jsoning/foundations/mapper.rb', line 10

def custom_block
  @custom_block
end

#default_valueObject

Returns the value of attribute default_value.



6
7
8
# File 'lib/jsoning/foundations/mapper.rb', line 6

def default_value
  @default_value
end

#nameObject



27
28
29
30
# File 'lib/jsoning/foundations/mapper.rb', line 27

def name
  @name_as_string = @name.to_s if @name_as_string.nil?
  @name_as_string
end

#nullableObject



18
19
20
21
22
23
24
25
# File 'lib/jsoning/foundations/mapper.rb', line 18

def nullable
  if @nullable.is_a?(TrueClass) || @nullable.is_a?(FalseClass)
    return @nullable
  else
    # by default, allow every mapped things to be nil
    true
  end
end

#parallel_variableObject

what variable in the object will be used to obtain the value



9
10
11
# File 'lib/jsoning/foundations/mapper.rb', line 9

def parallel_variable
  @parallel_variable
end

Instance Method Details

#extract(object, target_hash) ⇒ Object

map this very specific object’s field to target_hash



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jsoning/foundations/mapper.rb', line 33

def extract(object, target_hash)
  if object.respond_to?(parallel_variable)
    parallel_val = object.send(parallel_variable)
    parallel_val = default_value if parallel_val.nil?
    target_hash[name] = deep_parse(parallel_val)
  else
    if default_value
      target_hash[name] = deep_parse(default_value)
    else
      unless nullable
        raise Jsoning::Error, "Null value given for '#{name}' when serializing #{object}"
      end
    end
  end
end