Class: ActionController::Parameters

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

Instance Method Summary collapse

Instance Method Details

#extract_json_apiObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/json_api_params.rb', line 11

def extract_json_api
  case data = fetch(:data)
  when Array
    return data.map {|_data|
      self.class.new(data: _data).extract_json_api
    }
  end

  relationships = data.fetch(:relationships) { self.class.new }.to_unsafe_hash.map {|key, value|
    [key.underscore, value]
  }.to_h

  attributes = data.fetch(:attributes) { self.class.new }.to_unsafe_hash.map {|key, value|
    [key.underscore, value]
  }.to_h

  extracted = relationships.each_with_object(attributes) {|(key, value), attrs|
    case _data = value.fetch('data')
    when Array
      attrs["#{key}_ids"] = _data.map {|item|
        item.fetch('id')
      }
    when nil
      attrs["#{key}_id"] = nil
    else
      attrs["#{key}_id"] = _data.fetch('id')
    end
  }

  self.class.new(extracted)
end