E 'possibile lavorare con HTTParty risultati richiesta come un oggetto
-
25-09-2019 - |
Domanda
Mi chiedo se è possibile lavorare con HTTParty risultati richiesta come un oggetto.
Attualmente io uso chiavi di stringa per l'accesso ai valori del risultato: result["imageurl"]
o result["address"]["street"]
Se fossi in JavaScript ho potuto utilizzare semplicemente: result.imageurl
o result.address.street
Soluzione
Utilizzare la classe Mash
del hashie gemma.
tweet = Hashie::Mash.new(
HTTParty.get("http://api.twitter.com/1/statuses/public_timeline.json").first
)
tweet.user.screen_name
Altri suggerimenti
questa classe di supporto qualche giorno fa:
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
Esempio di utilizzo:
ojson = ObjectifiedHash.new(HTTParty.get('http://api.dribbble.com/players/simplebits'))
ojson.shots_counts # => 150
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow