Relative Path Problem in Sinatra View

I use the following code to check for the existence of a file before posting the image in my erb file. This ruby ​​/ sinatra app is 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 in Heroku, it obviously won't work.

I tried using the relative path, but I cannot get it to work:

 <% if FileTest.exist?( "/" + @imagename ) %> 
+4
source share
2 answers

A path starting with / is not a relative path, it is an absolute path. He says go to root and then go to next path

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

Then try the relative path from this folder to the image. for example, if the application works with /Users/Tim/projects/game , then the relative path to the public is just public , so the path to the image will be File.join('public', @imagename)

If you need more help send the Dir.pwd value from both environments


Here is another approach:

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

Using this, in the .rb file that launches your application, set the constant as follows:

 APP_ROOT = File.dirname(__FILE__) 

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

Then, in your opinion, you can use:

 FileTest.exist?(File.join(APP_ROOT, 'public', @imagename)) 
+9
source

That you want to use the RAILS_ROOT constant points to your application folder. Thus, on your local machine RAILS_ROOT will be evaluated /Users/Tim/projects/game/ .

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

0
source

Source: https://habr.com/ru/post/1309467/


All Articles