Question

Ruby on Rails 3.2, I have a table that shows files by basename. I would like to show a thumbnail next to the name of the file type. So if its a pdf file I would show a little image indicating its a pdf file. The files show the file type but I would like an image also to make it easier to pick out.

This is my loop for my table showing the file names only. How would I add a image based on the file type?

<tbody>
  <% @files.each do |file| %>
    <tr>
      <td><%= link_to File.basename(file).upcase, file[/\/.*/] %></td>
    </tr>
  <% end %>
</tbody>

This is one example of a file being viewed.

ENGLISH_FACTSHEET2013_V3.PDF

I am hoping there is a gem or something.

Was it helpful?

Solution

A simple approach could be a helper that checks for the file extension with some regex or some simple string comparison, then creates a image_tag based on the type:

def extension_image(file_name)
  if file_name.upcase.include?('.PDF')
    image_tag 'pdf.png'
  elsif file_name.upcase.include?('.JPG')
    ...
  ...
end

Then on your view:

<td>
  <%= extension_image(File.basename(file)) %>
  <%= link_to File.basename(file).upcase, file[/\/.*/] %>
</td> 

OTHER TIPS

Try to use:

file.content_type

It should return something like "application/pdf"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top