Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing/linking to contents of directory in Rails

I have a set of static PDFs. I want to list them out on a rails page, with links to them.

What I need right now is how to trim the /public off the beginning of the path so the link will actually work.

Current code:

<h1>Listing letters</h1>
<table>
<ul>
<% @files = Dir.glob("public/files/*.pdf") %>
<% for file in @files %>
<% new_file = file.to_s %>
<% new_file = new_file.chomp("public/") %>
<li><%= link_to 'Letter', new_file %></li>
<% end %>
</ul>
</table>

However the links are still coming as

http://localhost:3000/public/files/document.pdf

when to work they need to be

http://localhost:3000/files/document.pdf
like image 426
DVG Avatar asked Apr 27 '11 13:04

DVG


2 Answers

<% Dir["public/files/*.pdf"].each do |file| %>
  <li><%= link_to 'Letter', file[/\/.*/] %></li>
<% end %>
like image 52
fl00r Avatar answered Nov 07 '22 09:11

fl00r


The chomp method is used to remove someting at the end of the string ;) Use gsub instead.

new_file.gsub!('public', '')

or

new_file = new_file.gsub('public', '')
like image 23
Icid Avatar answered Nov 07 '22 09:11

Icid