I'm trying to fetch some products from this JSON API so I can display them in my views, with bad JSON gracefully handled using Hash#fetch
to declare a default value if I get nil.
But why am I getting:
can't convert String into Integer
or if I set @json_text
to {}
:
undefined method 'fetch' for `nil:NilClass`
Live app: http://runnable.com/U-QEWAnEtDZTdI_g/gracefully-handle-bad-json
class MainController < ApplicationController
require 'hashie'
def index
@json_text = <<END
{
"products": []
}
END
hashes = JSON.parse(@json_text)
mashes = Hashie::Mash.new(hashes)
products = []
mashes.products.fetch('products', []).each do |mash|
puts "YOLO"
end
end
end