How to DRY up method with multiple { 'not found' }?

后端 未结 2 416
情话喂你
情话喂你 2021-01-16 22:36

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):

<
相关标签:
2条回答
  • 2021-01-16 23:27

    As per the clarification in the comments, I will also answer. My solution is much the same as Зелёный's, but it takes dynamic attribute setting into account

    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
    
    0 讨论(0)
  • 2021-01-16 23:30

    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
    
    0 讨论(0)
提交回复
热议问题