I have a jbuilder to show my object.
Thats how it looks (part of it)
o = @property_object
json.features o.property_object_feature_pack, :pool, :garage, terrace
and this showing me next:
{
features: {
pool: {
params: null,
present: "false"
},
garage_parking: {
params: null,
present: "false"
},
terrace_balcony: {
params: null,
present: "true"
}
}
}
Question is that I don't want to show in output features with present: "false" . To solve this I write next code
json.features o.property_object_feature_pack, :pool if o.property_object_feature_pack.pool['present'] === "true"
json.features o.property_object_feature_pack, :garage_parking if o.property_object_feature_pack.garage_parking['present'] === "true"
json.features o.property_object_feature_pack, :terrace_balcony if o.property_object_feature_pack.terrace_balcony['present'] === "true"
And it works - but looks awful. How it can be refactored?
Next problem that it can be new features to be added in ActiveRecord in future, and I want to know can we iterate over o.property_object_feature_pack without setting names ? (:pool, :garage_parking etc.. )
ps. raw o.property_object_feature_pack
features: {
id: 820,
property_object_id: 56879,
created_at: "2015-04-27T18:25:25.712Z",
updated_at: "2015-04-27T18:25:25.712Z",
pool: {
params: null,
present: "false"
},
garage_parking: {
params: null,
present: "false"
},
terrace_balcony: {
params: null,
present: "true"
},
av_apartments: {
params: null,
present: "false"
}
}
Updated
Inspired by #mudasobwa I had create a little helper method that solves my question
def features_list
@property_object.property_object_feature_pack.as_json.select! do |_, v|
v.is_a?(Hash) && v['present'] == 'true'
end
end
I have no clue about what jbuilder
is, but I would suggest to convert json into plain ruby hash, do whatever you want and convert it back into json:
require 'json'
hash = JSON.parse what_you_got_from_builder
hash[:features].select! do |_, v|
!v.is_a?(Hash) || v[:present] == 'true'
end
hash.to_json