开发者

Relative path issue within Sinatra view

开发者 https://www.devze.com 2022-12-30 03:25 出处:网络
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.

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 ) %> 


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))


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号