【问题标题】:How to DRY up method with multiple { 'not found' }?如何用多个 { 'not found' } 干燥方法?
【发布时间】:2014-08-09 06:04:23
【问题描述】:

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

【问题讨论】:

  • 产品价格总是以 deep_fetch :currency 的值结束,不是吗?
  • 不,:sale_price:currency 是两个不同的值。
  • @dax 指的是您分配给product.price 三次的事实,并且想知道(和我一样)您是否打算分配给不同的属性。
  • 糟糕!那是一个错字!抱歉,@dax,Amadan。问题已编辑。
  • @Amadan,没错 - 马克,我添加了一个我认为根据更新信息更合适的答案。

标签: ruby-on-rails ruby json hash


【解决方案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

【讨论】:

    【解决方案2】:

    根据 cmets 中的说明,我也会回答。我的解决方案和Зелёный的解决方案差不多,但它需要考虑动态属性设置

    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
    

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多