开发者

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

开发者 https://www.devze.com 2023-01-14 08:34 出处:网络
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 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号