Reputation: 1709
I have a scenario where I want to set a json attribute to nil if its object value is nil within a jbuilder block:
example of how I'm doing it now:
unless obj.details.nil?
json.details do |json|
json.value1 obj.details.value1
json.value2 obj.details.value2
end
else
json.details nil
end
My question is there a cleaner way to do this so I don't have to use an unless/else
Upvotes: 4
Views: 1412
Reputation: 41
You can use a combination of tap
and json.nil!
for this.
json.details do
obj.details&.tap do |details|
json.value1 details.value1
json.value2 details.value2
end || json.nil!
end
OR
json.details do
obj.details.tap do |details|
return json.nil! if details.nil?
json.value1 details.value1
json.value2 details.value2
end
end
Upvotes: 4