Class: Freelancer::Support::JSONMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/freelancer/support/json_mapper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ JSONMapper

Initialize the JSON mapper



9
10
11
12
# File 'lib/freelancer/support/json_mapper.rb', line 9

def initialize(model)
  @model = model
  @mappings = {}
end

Instance Attribute Details

#mappingsObject (readonly)

Returns the value of attribute mappings.



6
7
8
# File 'lib/freelancer/support/json_mapper.rb', line 6

def mappings
  @mappings
end

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/freelancer/support/json_mapper.rb', line 5

def model
  @model
end

Instance Method Details

#from_json(json) ⇒ Object

Populate the fields of the model by mapping the JSON data structure specified against the model attributes.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/freelancer/support/json_mapper.rb', line 45

def from_json(json)
  
  json.each_pair do |key, value|
    
    # If our value is a hash and it's mapped by the mapper,
    # do a special hash lookup on the map target
    # for each of the key+nested key combinations
    if value.is_a?(Hash) && mapped_as_hash?(key)

      value.each_pair do |nested_key, nested_value|
        map_key = mapped_from({ key => nested_key })
        raise ArgumentError.new("Unable to map key #{{ key => nested_key }.inspect} to model attribute") if map_key.nil?
        model[map_key] = nested_value
      end
      
    else
      map_key = mapped_from(key)
      raise ArgumentError.new("Unable to map key #{key} to model attribute") if map_key.nil?
      model[map_key] = value
    end
  

  end
  
  model
            
end

#map(from, to) ⇒ Object

Map a key against the given model value



15
16
17
# File 'lib/freelancer/support/json_mapper.rb', line 15

def map(from, to)
  @mappings[from] = to
end

#to_jsonObject

Build a JSON data structure of the current mapping according to the format specifications from the Freelancer.com API.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/freelancer/support/json_mapper.rb', line 21

def to_json
  
  # Build a Hash of the current mappings
  structure = {}
  mappings.each_pair do |from, to|
    
    # If our "to" is a hash, build a nested hash into the structure
    if to.is_a?(Hash)
      
      structure[to.keys.first] ||= {}
      structure[to.keys.first][to.values.first] = model[from]
      
    else
      structure[to] = model[from]
    end

  end
  
  structure

end