I'm using an API with Ruby. I've constructed my own model that will work with HTTParty to go up to an api and grab the data. Here's an example of what I'm doing:
tweets = Twitter::Tweets.all
first_tweet = tweets.first
This does not return any errors, but inside tweets
we now have a list of all of our tweets. (We store this in a NoSQL DB for performance and rate limiting issues.) Now then, we want to know when our first tweet was created:
first_tweet.created_at
# => undefined method `created' for #<Hash:0x007ff3491062d0>
Well that sucks... OK. Its a Hash, so we try:
first_tweet['created_at']
# => "2014-04-07T08:37:47+00:00"
Awesome! But, I'm going to be doing this a lot.
Key Question: Is there a way to use methods instead of keys?
Edit:
I'm understanding that I can either use OpenStruct
or a gem for this. Thanks for letting me know. I guess the question now becomes: Is there an effective (and DRY) way to implement this into a model?
Here's what our model would may look like:
# app/models/twitter/tweet.rb
module Twitter
class Tweet < Twitter::Base
class << self
def all
get '/v1/tweets.json'
end
end
end
end
And Twitter::Base
is, to keep it brief, our configuration:
# app/models/twitter/base.rb
module Twitter
class Base < ActiveRecord::Base
include HTTParty
base_uri 'api.twitter.com'
format :json
default_params api_password: ENV['TWITTER_PASSWORD']
end
end
Although, I could do:
def all
tweets = get('/v1/tweets.json')
array = []
tweets.each do |tweet|
array << OpenStruct.new(tweet)
end
return array
end
But this would be a lot of work to write an openstruct per every method. I think I'll explore it and answer my own question in the next few days if no one knows of a DRY and scalable way to implement this.
Reminder: Not actually dealing with the twitter api, but the use case stays the same.