我试图优雅地处理以下错误的JSON,其中Hash#fetch
似乎不是一个选项(Handle bad JSON gracefully with Hash#fetch):
直播应用: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 << product
end
但有没有办法干这个?
已编辑:根据@dax
的讨论更新答案 0 :(得分:1)
我不确定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
答案 1 :(得分:1)
根据评论中的澄清,我也会回答。我的解决方案与Зелёный相同,但需要考虑动态属性设置
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