Search code examples
rubyimagefilemiddleman

Check if image file exists using middleman


I have a website running on middleman. I'm trying to check if an image file exists. I followed the suggestion in "How to check for file existence", using File.file?, but it's not working. Here's the line of code:

<% if File.exists?("/source/images/doctor-#{doctor.slug}.jpg") %>

I tried a few different file paths:

  • /source/images/file
  • /images/file
  • ../images/file

but none worked. In the browser, I can view the image file at "0.0.0.0:4567/images/file".

Any ideas?


Solution

  • Maybe it's easier to query those files via the Middleman Sitemap?

    You gain access to it within templates via the sitemap object. One way of achieving your actual case could be:

    <% if sitemap.find_resource_by_path("images/doctor-#{doctor.slug}.jpg") %>
        <%# do what you want %>
    <% end %>