Skip to content

Instantly share code, notes, and snippets.

@ursm
Last active October 10, 2015 08:46
Embed
What would you like to do?
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