Class: Praxis::MediaType::FieldResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/praxis/media_type.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFieldResolver

Returns a new instance of FieldResolver.



94
95
96
97
98
# File 'lib/praxis/media_type.rb', line 94

def initialize
  @history = Hash.new do |hash,key|
    hash[key] = Hash.new
  end
end

Instance Attribute Details

#historyObject (readonly)

Returns the value of attribute history.



92
93
94
# File 'lib/praxis/media_type.rb', line 92

def history
  @history
end

Class Method Details

.resolve(type, fields) ⇒ Object



88
89
90
# File 'lib/praxis/media_type.rb', line 88

def self.resolve(type,fields)
  self.new.resolve(type,fields)
end

Instance Method Details

#deep_merge(target, source) ⇒ Object

perform a deep recursive *in place* merge form all values in source onto target

note: can not use ActiveSupport’s Hash#deep_merge! because it does not properly do a recursive ‘deep_merge!`, but instead does `deep_merge`, which destroys the self-referential behavior of field hashes.

note: unlike Hash#merge, doesn’t take a block.



153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/praxis/media_type.rb', line 153

def deep_merge(target, source)
  source.each do |current_key, source_value|
    target_value = target[current_key]

    target[current_key] = if target_value.is_a?(Hash) && source_value.is_a?(Hash)
      deep_merge(target_value, source_value)
    else
      source_value
    end
  end
  target
end

#resolve(type, fields) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/praxis/media_type.rb', line 100

def resolve(type,fields)
  history_key = fields
  history_type = type
  if fields.kind_of?(Array)
    loop do
      type = type.member_attribute.type
      fields = fields.first
      break unless fields.kind_of?(Array)
    end
  end

  return true if fields == true

  if history[history_type].include? history_key
    return history[history_type][history_key]
  end

  result = history[history_type][history_key] = {}


  fields.each do |name, sub_fields|
    # skip links and do them below
    next if name == :links && defined?(type::Links)

    new_type = type.attributes[name].type
    result[name] = resolve(new_type, sub_fields)
  end

  # now to tackle whatever links there may be
  if (links_fields = fields[:links])
    resolved_links = resolve_links(type::Links, links_fields)
    self.deep_merge(result, resolved_links)
  end

  result
end


137
138
139
140
141
142
143
# File 'lib/praxis/media_type.rb', line 137

def resolve_links(links_type, links)
  links.each_with_object({}) do |(name, link_fields), hash|
    using = links_type.links[name]
    new_type = links_type.attributes[name].type
    hash[using] = resolve(new_type, link_fields)
  end
end