Question

I wonder if it possible to work with 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

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top