Ruby on rails 何时使用Hashie::Mash?
正在从这个JSON API获取一些产品,我想知道——我真的需要Ruby on rails 何时使用Hashie::Mash?,ruby-on-rails,ruby,json,hash,Ruby On Rails,Ruby,Json,Hash,正在从这个JSON API获取一些产品,我想知道——我真的需要Hashie::Mash 实时应用程序: 主控制器.rb: response = prettify(JSON.parse(@json_text)) mashie = Hashie::Mash.new(response) @products = [] mashie.products.each do |product| product.extend Hashie::Extensions::DeepFetch product.p
Hashie::Mash
实时应用程序:
主控制器.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
您可能希望执行以下操作:
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
mashie.products.each do|产品|
product.extend Hashie::Extensions::DeepFetch
product.price=product.deep\u fetch(:sale\u price){“未找到”}
#如果未找到关键销售价格,则返回“未找到”。它可以是任何内容,如nil、0、“未找到”
@所以在这个意义上我可以删除Hashie::Mash.new(response)
?基本上,我只是尽量简化代码。我不知道为什么我首先需要Hashie::Mash
(因为我不需要做product.price?
等)。你不能,因为你需要它来访问像mashie.products
这样的项目。看起来这是一种在json上迭代产品的好方法。
Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price
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