Check if a file exists in Rails

February 21, 2009

 
No Gravatar

Recently I was porting a legacy PHP application to Rails. One of the primary tasks was to resize a bunch of images. Below you can see what one of the database rows looks like.

mysql> SELECT id, filename FROM old_posts
+----+---------------------------------------+
| id | filename                              |
+----+---------------------------------------+
|  1 | unxplained-photo-1225258423-85706.jpg |
+----+---------------------------------------+
1 row in set (0.00 sec)                                                                   
 
mysql>

You’ll see that the name of the filename is stored in the database, the problem I encountered was that often times the actual file didn’t exist even though the record remained in the database.

Rails would get angry at me when I tried to resize an non-existent file. To account for this, I did the following:

if FileTest.exists?(filename)
 # some code here to
 # resize the image
end

For more information on this handy ruby module pop into the docs.

  • hmmm its usefull info of ruby on rails
  • ajay
    thanks a lot.. i had written a function to do the same thing...but when you so beautifully described it in a line.. take care.. cheers !
  • I bet I should use this like <div class="clear"></div>. All over the place!
blog comments powered by Disqus