Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative path issue within Sinatra view

Tags:

ruby

erb

sinatra

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 ) %> 
like image 273
tim roberts Avatar asked Jan 22 '23 02:01

tim roberts


1 Answers

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))
like image 168
mikej Avatar answered Mar 07 '23 20:03

mikej