Last active
October 10, 2015 08:46
-
-
Save ursm/dc081cb4363aa7ff3def to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActionController::Parameters | |
def destruct_jsonapi | |
data = fetch(:data) | |
relationships = data.fetch(:relationships) { self.class.new } | |
attributes = self.class[*data.fetch(:attributes) { Hash.new }.flat_map {|key, value| | |
[key.underscore, value] | |
}] | |
relationships.each_with_object(attributes) {|(key, value), attrs| | |
k = key.underscore | |
case _data = value.fetch(:data) | |
when Array | |
attrs["#{k}_ids"] = _data.map {|item| | |
item.fetch(:id) | |
} | |
else | |
attrs["#{k}_id"] = _data.try(:fetch, :id) | |
end | |
} | |
end | |
end | |
ActionController::Parameters.new( | |
data: { | |
attributes: { | |
'x-y': 1, | |
z: 2 | |
}, | |
relationships: { | |
'foo-bar': { | |
data: { | |
id: 42 | |
} | |
}, | |
baz: { | |
data: nil | |
}, | |
qux: { | |
data: [{ | |
id: 3 | |
}, { | |
id: 4 | |
}] | |
} | |
} | |
} | |
).destruct_jsonapi.permit(:x_y, :z, :foo_bar_id, :baz_id, :qux_ids => []) | |
#=> {"x_y"=>1, "z"=>2, "foo_bar_id"=>42, "baz_id"=>nil, "qux_ids"=>[3, 4]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment