如何使用多个{'not found'}干掉方法? [英] How to DRY up method with multiple { 'not found' }?
问题描述
我正在尝试为下面的内容正常处理坏的JSON,其中 Hash#fetch
似乎不是一个选项(用Hash#fetch 优雅地处理坏的JSON):
直播应用: http://runnable.com/U-QJCIFvY2RGWL9B/pretty- json-keys ( main_controller.rb
)
所以显然最好的方法是添加 {'not found'}
到每个参数的结尾:
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<<产品
结束
但是有没有办法干这个呢?
已编辑:根据与@dax的讨论进行更新
我对 product.price = product.deep_fetch(属性,{'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属性{'未找到'}
结束
@products<<产品
结束
I'm trying to gracefully handle bad JSON for the following, where Hash#fetch
doesn't seem to be an option (Handle bad JSON gracefully 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 up?
Edited: Updated as per discussion with @dax
I not sure about right 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
这篇关于如何使用多个{'not found'}干掉方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!