RossRobertMcKee RossRobertMcKee - 1 year ago 36
Ruby Question

`File.exist?` won't find file that exists

I'm trying to use

to have a dynamic background. When I try to to point File.exist? to a specific file it doesn't seem to find it.

image_path = "../assets/" + city_code + ".jpg"
@image = image_path
@image = "../assets/coastbanner.jpg"

If I remove replace
with a path that I know exists, it still won't find it. I must bee missing something small.

I wanted to be a little more clear: If I remove the interpolation/variable and replace it with a path that I know works, '../assets/coastbanner.jpg' for example, it still will not work. In fact, no valid path seems to get it to yield a true response.


There are some issues with your code:

  • String interpolation works only with double quotes
  • There is no need for a string interpolation when the variable is a string already
  • the condition belongs in the same line than the if

Furthermore the folder in which the server is running might not be the same folder than the current webpage is served from. That said it might make sense to use absolute path for image links and path including Rails.root for the File.exist? test.

I am not sure about your application's folder structure, but something like the following should work:

image_path = "/assets/#{city_code}.jpg"

if File.exist?(Rails.root.join('app', image_path))
  @image = image_path
  @image = '/assets/coastbanner.jpg'

Tip: Test with the coastbanner.jpg to get the image apth correct and then with the File.exist? to get the path in the app.