Ever write code like this in Rails?
if File.exists?(File.join(RAILS_ROOT, 'config', 's3.yml')) has_attached_file :s3_image, :storage => :s3, :s3_credentials => File.join(RAILS_ROOT, 'config', 's3.yml') end
That particular snippet is from an application that optionally uses Amazon S3 to store images, if there is a configuration file for S3 supplied in the deployment. Well, you can clean that up a bit. First, although the RAILS_ROOT constant is still supported, we’ve had the prettier-looking Rails.root for months. Second, as of a recent commit to edge rails, Rails.root returns a Pathname object, so it directly supports the join method. Hence, the code snippet above can now be:
if File.exists?(Rails.root.join('config', 's3.yml'))
has_attached_file :s3_image,
:storage => :s3,
:s3_credentials => Rails.root.join('config', 's3.yml')
end
A tiny improvement, but of such tiny improvements are a pleasant framework made.


4 comments
Comments feed for this article
December 5, 2008 at 5:18 pm
Mark Wilden
Nice tip. I’d stick Rails.root.join(’config’, ’s3.yml’) in a local variable instead of repeating it.
December 5, 2008 at 7:06 pm
Dan Kubb
Pathname is IMHO one of the more useful, but most underused libraries. It makes working work files alot simpler than using the File class directy.
Although I’d probably tend to write that example using the Pathname#exists? method instead of File.exists?, like this: http://pastie.org/332348
December 6, 2008 at 7:12 am
Mike Gunderloy
The nicest thing about posting code samples: instant code review. Thanks, good changes both.
March 9, 2009 at 5:12 am
ChrisR
1. File.join() – which all developers will only understand
or
2. Rails.root.join() – which will only make sense to rails developers
I think its a pointless change that makes it slightly cleaner, but less understandable overall.