tags:

views:

73

answers:

2

I am using the following code to check existence of a file before publishing an image in my erb file. This is a ruby/sinatra app - not rails.

<% @imagename = @place.name + ".jpg" %> 
<% if FileTest.exist?( "/Users/Tim/projects/game/public/" + @imagename ) %> 
<p><img src= '<%= @imagename %>' width="400" height="300" /> </p> 
<% end %> 

And when I publish this to Heroku, it obviously won't work.

I tried using a relative path, but I'm unable to get it to work:

<% if FileTest.exist?( "/" + @imagename ) %> 
+5  A: 

A path starting with a / is not a relative path, that's an absolute path. It says go to the root and then navigate down to the following path

The first step is to check where your app is running from. i.e. what is the current directory. To do this temporarily put <%= Dir.pwd %> in your view and try this both locally and on Heroku to compare the two environments.

Then try a relative path from this folder to the image. e.g. If the app is running from /Users/Tim/projects/game then the relative path to public is just public so the path to the image would be File.join('public', @imagename)

If you need more help then please post the value of Dir.pwd from both environments


Here is another approach:

__FILE__ is a special Ruby variable that gives a relative path to the current file.

Making use of that, in the .rb file that starts your app set a constant as follows:

APP_ROOT = File.dirname(__FILE__)

(a similar line in an app's config.rb is used to set RAILS_ROOT in a Rails app)

Then in your view you can use:

FileTest.exist?(File.join(APP_ROOT, 'public', @imagename))
mikej
how do i do this in Sinatra?
tim roberts
Updated for Sinatra above. Let me know if this helps.
mikej
This approach worked:"Then try a relative path from this folder to the image. e.g. If the app is running from /Users/Tim/projects/game then the relative path to public is just public so the path to the image would be File.join('public', @imagename)"The APP_ROOT approach game me an unitilized constant error. now working. thanks MikeJ!
tim roberts
Cool. glad it's working now. To get the constant to work it might just need a bit of tweaking for the specifics of your app.
mikej
A: 

What you want to is use the RAILS_ROOT constant - it points to your app's folder. So on your local machine RAILS_ROOT will evaluate to /Users/Tim/projects/game/.

This is Rails specific, use File.dirname(__FILE__) instead.

Jakub Hampl
really? in a sinatra app?
Matt Briggs
This was clarified after the solution was posted. In this case `File.dirname(__FILE__)` would probably do the trick.
Jakub Hampl