Archive for August, 2009

Migrating up and down quickly

Thursday, August 27th, 2009

I frequently make a migration, migrate, run my tests and realize there’s a bug with my migration, or I forgot something, or whatever. It’s kind of annoying to have to type:

rake db:migrate
rake db:migrate RAILS_ENV=test
# run tests, watch tests fail
rake db:rollback
rake db:rollback RAILS_ENV=test
# fix code and repeat

… over and over and over. So I wrote a couple little rake tasks:

task :mig do
  dev_and_test("migrate")
end
 
task :roll do
  dev_and_test("rollback")
end
 
def dev_and_test(what)
  ["development", "test"].each do |env|
    system "rake db:#{what} RAILS_ENV=#{env}"
  end
end

Now I can just do:

rake mig
# run tests, fail
rake roll
#fix code, rinse, repeat

Much nicer.

Strip leading zeros in string formatting

Wednesday, August 26th, 2009

There is lots of talk out there about how to strip leading zeros from dates and times in Ruby and PHP. Ruby’s documentation on the subject is woefully inadequate.

The problem is that many of the format tokens they list have leading zeroes. So if I format todays date like so:

Date.today.strftime("%m/%d")

… It will tell me it’s “08/26″. Note the leading zero.

Some people will tell you to use %j and %e instead of %m and %d, which seems to work in newer versions of Ruby. Other people use elaborate regular expressions to clean up their dates after formatting them.

But the best advice I’ve found is in the comment on this post: Just put a -1 in each format token like so:

Date.today.strftime("%-1m/%-1d")

That expression will return “8/26″. The -1 basically means “print this number, but strip off up to 1 zero before you do.”

Seems like a more proper way to do things.

Search bait: zeroes, sprintf, format, padding, date, time, datetime, rails