4

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

John Bachir
  • 22,495
  • 29
  • 154
  • 227
Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197

2 Answers2

10

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
John Bachir
  • 22,495
  • 29
  • 154
  • 227
Chubas
  • 17,823
  • 4
  • 48
  • 48
3

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
Community
  • 1
  • 1
Daniel O'Hara
  • 13,307
  • 3
  • 46
  • 68