【问题标题】:Is it possible to work with HTTParty request results as an object是否可以将 HTTParty 请求结果作为对象使用
【发布时间】:2010-08-31 04:16:09
【问题描述】:

我想知道是否可以将HTTParty 请求结果作为对象使用。

目前我使用字符串键来访问结果值:result["imageurl"]result["address"]["street"]

如果我使用的是 JavaScript,我可以简单地使用:result.imageurlresult.address.street

【问题讨论】:

    标签: ruby-on-rails ruby xml json httparty


    【解决方案1】:

    使用hashie gem 的Mash 类。

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

    【讨论】:

      【解决方案2】:

      我几天前写了this helper class

      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
      

      使用示例:

      ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits'))
      ojson.shots_counts # => 150
      

      【讨论】:

        猜你喜欢
        • 2016-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多