何时使用Hashie :: Mash?

Mar*_*der 2 ruby hash json ruby-on-rails

努力从这个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
Run Code Online (Sandbox Code Playgroud)

我试过这个:

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
Run Code Online (Sandbox Code Playgroud)

但是返回:

Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price
Run Code Online (Sandbox Code Playgroud)

Thi*_*ges 5

你可能想做这样的事情:

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
Run Code Online (Sandbox Code Playgroud)