So for TodaysCigar.com I wanted to tweet the day’s cigar each night, just as Woot does.  This way anyone following the @todayscigar twitter account could instantly see the daily posting, and look back at past days’ cigars.  Fortunately, some members of the Ruby community have released Twitter gems – namely the Ruby Twitter Gem and the Twitter4R gem.  Both are extremely easy to use, but I opted for the Twitter4R gem.  The Ruby Twitter Gem is excellent, but it’ll track multiple twitter accounts and it wants you to run some migrations on your database.  I didn’t want to update my DB schema, so I went with twitter4r.  Once the twitter4r gem was installed, all I had to do was write up a quick rake task, then setup a cron job to fire it off every night after midnight.

So first was the installation of twitter4r…

sudo gem install twitter4r

Next, I created a new rake task in lib/tasks called twitter_poster.rake.

desc “Posts the current days’ cigar to the twitter account.”
task :twitter_poster => :environment do
end

Next, I added a couple of lines to my various environment files (development.rb, etc) to indicate my login/password for my dev and production twitter accounts. This way my passwords won’t be floating around in the code, and it’s easy to test on multiple environments.

ENV["TWITTER_ACCOUNT"] = “login_name”
ENV["TWITTER_PASSWORD"] = “password”

Going back to the twitter_poster.rake file, I included the twitter4r gem, and was able to set up a new Twitter client and post my first status.

desc “Posts the current days’ cigar to the twitter account.”
task :twitter_poster => :environment do
require ‘twitter’

client = Twitter::Client.new(:login => ENV['TWITTER_ACCOUNT'], :password => ENV['TWITTER_PASSWORD'])

new_message = client.status(:post, “Welcome to the TodaysCigar.com Twitter feed.”)
end

Throwing in some code to actually pull the current cigar, and I’ve got a workable rake task.

desc “Posts the current days’ cigar to the twitter account.”
task :twitter_poster => :environment do
require ‘twitter’

@product = Product.todays_item
if (@product.nil?)
@product = Product.default_item
end

client = Twitter::Client.new(:login => ENV['TWITTER_ACCOUNT'], :password => ENV['TWITTER_PASSWORD'])

new_message = client.status(:post, “Today’s cigar is the #{@product.title}, for only $#{@product.price}. http://www.todayscigar.com”)

puts “Twitter posting complete.”
end

Then all I had to do was add an entry to /etc/crontab to kick off the rake task each night.

Thank you, Twitter4R!

Tags:

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>