如何使用多个 { 'not found' DRY up 方法}? [英] How to DRY up method with multiple { 'not found' }?
问题描述
我正在尝试优雅地处理以下错误的 JSON,其中 Hash#fetch
似乎不是一个选项(使用 Hash#fetch 优雅地处理错误的 JSON):
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):
实时应用:http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys (main_controller.rb
)
显然最好的方法是在每个参数的末尾添加 { 'not found' }
:
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
但是有没有办法把它弄干?
已根据与@dax 的讨论进行更新
Edited: Updated as per discussion with @dax
推荐答案
我不确定 product.price = product.deep_fetch(attribute, { 'not found' })
中的正确语法:
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
这篇关于如何使用多个 { &#39;not found&#39; DRY up 方法}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!