Is it possible to work with HTTParty request results as an object
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"]
I开发者_StackOverflow中文版f i were in JavaScript I could simply use: result.imageurl
or result.address.street
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
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
精彩评论