Updating Twitter from Ruby/Rails
I believe in sharing knowledge, so here is the method to achieve a Twitter update from Ruby (using POST, as GET is now disabled by Twitter for security reasons). This code requires Ruby 1.8.5 for the set_form_data method.
With Ruby on Rails, the following is best placed in a controller. This probably isn’t the only way of doing it, but if you’re looking for something that ‘just works’ this is it. You might want to add some flash[:notice] alerts to let the user know what happened.
require 'net/http'
require 'uri'
twitter_email = 'example@whoever.com'
twitter_password = 'urpassw0rdhere'
update_text = 'Testing Twitter update using Ruby code!'
begin
url = URI.parse('http://twitter.com/statuses/update.xml')
req = Net::HTTP::Post.new(url.path)
req.basic_auth twitter_email, twitter_password
req.set_form_data({'status' => update_text})
begin
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
if res.body.empty?
# Twitter is not responding properly
else
# Twitter update succeeded
end
else
# Twitter update failed for an unknown reason
res.error!
end
rescue
# Twitter update failed - check username/password
end
rescue SocketError
# Twitter is currently unavailable
end
October 15th, 2007 at 3:15 pm
Thanks your article help me a lot
December 9th, 2007 at 11:21 pm
[...] to my post on How to update Twitter from Ruby/Rails, here is a method to verify account details. I got the idea from twitterfeed.com and pretty much [...]
July 24th, 2008 at 10:50 am
I must admit that I’m not so sure about Twitter and the value Twitter can give me. Personally, I don’t think it gives me any value, except waste my time. As a result, I’ve stopped using it altogether and found myself surviving fine. It didn’t do anything for my business, and stopping it has had no effect either. I guess it’s only valuable for certain people, but for me it hasn’t worked or done anything.
August 13th, 2008 at 10:09 am
Thanks for that. But surely if twitter has disabled the get and post methods for security reasons then it’s best not using them?
August 13th, 2008 at 10:51 am
Ah, Twitter disabled GET a long time ago, because GET is insecure. POST is more secure, and that is the way we are supposed to do it now.