Class: Jsoning::Mapper

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

Overview

responsible of mapping from object to representable values, one field at a time

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
  @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



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/jsoning/foundations/mapper.rb', line 50

def default_value
  if @default_value
    if @default_value.is_a?(Proc)
      return deep_parse(@default_value.())
    else
      return deep_parse(@default_value)
    end
  else
    nil
  end
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

#nullable=(value) ⇒ Object (writeonly)

Sets the attribute nullable

Parameters:

  • value

    the value to set the attribute nullable to.



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

def nullable=(value)
  @nullable = value
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
48
# File 'lib/jsoning/foundations/mapper.rb', line 33

def extract(object, target_hash)
  target_value = nil

  if object.respond_to?(parallel_variable)
    parallel_val = object.send(parallel_variable)
    target_value = deep_parse(parallel_val)
  end

  if target_value.nil?
    target_value = self.default_value
    if target_value.nil? && !self.nullable?
      raise Jsoning::Error, "Null value given for '#{name}' when serializing #{object}"
    end
  end
  target_hash[name] = deep_parse(target_value)
end

#nullable?Boolean

Returns:

  • (Boolean)


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