如何使用多个 { 'not found' DRY up 方法}? [英] How to DRY up method with multiple { 'not found' }?

查看:42
本文介绍了如何使用多个 { 'not found' DRY up 方法}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试优雅地处理以下错误的 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

这篇关于如何使用多个 { &amp;#39;not found&amp;#39; DRY up 方法}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆