Is it possible to work with the results of an HTTParty request as an object

I wonder if it is possible to work with HTTParty as a request object.

I am currently using string keys to access the values โ€‹โ€‹of the result: result["imageurl"] or result["address"]["street"]

If I were in JavaScript, I could just use: result.imageurl or result.address.street

+4
source share
2 answers

Use the Mash class hashie gem.

 tweet = Hashie::Mash.new( HTTParty.get("http://api.twitter.com/1/statuses/public_timeline.json").first ) tweet.user.screen_name 
+11
source

I wrote this helper class a few days ago:

 class ObjectifiedHash def initialize hash @data = hash.inject({}) do |data, (key,value)| value = ObjectifiedHash.new value if value.kind_of? Hash data[key.to_s] = value data end end def method_missing key if @data.key? key.to_s @data[key.to_s] else nil end end end 

Usage example:

 ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits')) ojson.shots_counts # => 150 
+3
source

All Articles