【问题标题】:When to use Hashie::Mash?何时使用 Hashie::Mash?
【发布时间】:2014-08-08 23:52:44
【问题描述】:

正在从这个 JSON API 获取一些产品,我想知道 -- 我真的需要Hashie::Mash吗?

直播应用:http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys

main_controller.rb:

response = prettify(JSON.parse(@json_text))
mashie = Hashie::Mash.new(response)

@products = []
mashie.products.each do |product|
  product.extend Hashie::Extensions::DeepFetch

  product.price = product.deep_fetch :sale_price

  @products << product
end
@products

我试过了:

response = prettify(JSON.parse(@json_text)['products'])

@products = []
response.each do |product|
  product.extend Hashie::Extensions::DeepFetch

  product.price = product.deep_fetch :sale_price

  @products << product
end
@products

但返回:

Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price

【问题讨论】:

    标签: ruby-on-rails ruby json hash


    【解决方案1】:

    你可能想做这样的事情:

    mashie.products.each do |product|
      product.extend Hashie::Extensions::DeepFetch
    
      product.price = product.deep_fetch(:sale_price) { 'Not Found' }
      # Returns 'Not Found' if it does not find the key sale_price. It can be anything, like nil, 0, 'Not Found'
    
      @products << product
    end
    

    【讨论】:

    • 所以在这个意义上我可以删除Hashie::Mash.new(response)?基本上我只是想尽可能地简化代码。我不知道为什么我首先需要Hashie::Mash(因为我不需要做product.price?等)。
    • 你不能因为你需要它来访问像mashie.products这样的项目。看起来这是在 json 上迭代产品的好方法。
    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多