views:

45

answers:

2

Hi guys,

I wonder if it possible to work with HTTParty (http://github.com/jnunemaker/httparty) request results as an object.

Currently i use string keys to access to values of result:

result["imageurl"] or result["address"]["street"]

If i were in JavaScript I could simply use:

result.imageurl or result.address.street

Regards, Alexey

+1  A: 

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
floatless
+2  A: 

Use the Mash class of the hashie gem.

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