How to dry out a method with multiple {'not found'}?
I'm trying to gracefully handle bad JSON for the following, where Hash#fetch
it doesn't seem to be an option ( handle JSON intelligently with Hash # fetch ):
Live app: http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys ( main_controller.rb
)
So apparently the best way is to add { 'not found' }
to the end of each argument:
mashie.products.each do |product|
product.extend Hashie::Extensions::DeepFetch
product.name = product.deep_fetch :name { 'not found' }
product.brand = product.deep_fetch :brand, :name { 'not found' }
product.price = product.deep_fetch :sale_price { 'not found' }
product.currency = product.deep_fetch :currency { 'not found' }
@products << product
end
But is there a way to DRY this?
Edited: Updated as discussion by @dax
source to share
I'm not sure about the correct syntax in product.price = product.deep_fetch(attribute, { 'not found' })
:
mashie.products.each do |product|
product.extend Hashie::Extensions::DeepFetch
i%[name sale_price currency].each do |attribute|
product.price = product.deep_fetch attribute { 'not found' }
end
@products << product
end
source to share
As explained in the comments, I'll answer as well. My solution is almost the same as Green, but it takes into account the dynamic value of the attribute
mashie.products.each do |product|
product.extend Hashie::Extensions::DeepFetch
i%[name sale_price currency].each do |attribute|
value = product.deep_fetch attribute { 'not found' }
product.send("#{attribute}=", value)
end
@products << product
end
source to share