When to use Hashie :: Mash?
Working on extracting some products from this JSON API and I was wondering - do I really need to Hashie::Mash
?
Live app: 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
I've tried this:
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
but returns:
Hashie::Extensions::DeepFetch::UndefinedPathError in MainController#index
Could not fetch path (sale_price) at sale_price
+2
source to share
1 answer
You probably want to do something like this:
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
+5
source to share