There is a plugin/gem called HTTParty that I've used for several projects.
http://johnnunemaker.com/httparty/
HTTParty lets you easily consume any web service and parses results into a hash for you. Then you can use the hash itself or instantiate one or more model instances with the results. I've done it both ways.
For the twitter example, your code would look like this:
class Twitter
include HTTParty
base_uri 'twitter.com'
def initialize(u, p)
@auth = {:username => u, :password => p}
end
# which can be :friends, :user or :public
# options[:query] can be things like since, since_id, count, etc.
def timeline(which=:friends, options={})
options.merge!({:basic_auth => @auth})
self.class.get("/statuses/#{which}_timeline.json", options)
end
def post(text)
options = { :query => {:status => text}, :basic_auth => @auth }
self.class.post('/statuses/update.json', options)
end
end
# usage examples.
twitter = Twitter.new('username', 'password')
twitter.post("It's an HTTParty and everyone is invited!")
twitter.timeline(:friends, :query => {:since_id => 868482746})
twitter.timeline(:friends, :query => 'since_id=868482746')
As a last point, you could use your code above also, but definitely include the code in a model as opposed to a controller.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…