Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails ruby iterate through partials in directory

To those helping.. Thanks. Still no solution but getting closer. The errors i think are because my "file" evaluates to "app/views/main/show/_partial.html.erb". and render adds it's own relative path. So I guess i need to list the file names.. maybe a dir.foreach or dir.glob type command.. i'll keep digging. THANKS!

I have a directory full of partials I would like to call in a page. So I wrote a loop but it yields errors.

<% Dir["app/views/main/show/*"].each do |file| %>
  <%= render #{file} %>
<% end %>

When I replace the render line with a simple

file

it lists the file names so i know the loop and Dir location work. The problem I THINK is that render is looking for a string. So I've tried all sorts of things from searching google and here like the #{file}, creating a variable first, raw,...etc.

also I think render may be looking in a different directory relative the Dir. I'll try out some stuff there to.

How should I be handling this? I'm up for switching from Dir to Dir.foreach or any other strategy that makes sense.

Thanks.

EDIT: Here's the solution I've implemented (directory path changed from above):

<% Dir["app/views/partials/show/*.html.erb"].each do |file| %>
<p> <%= render 'partials/show/' + File.basename(file,'.html.erb').slice!(1..-1) %></p>
<% end %>
like image 520
twinturbotom Avatar asked Feb 18 '23 18:02

twinturbotom


1 Answers

file is already a string, so there is no need to escape. Also, you have to give the full path. This should work:

<% Dir["app/views/main/show/*"].each do |file| %>
  <%= render :file => Rails.root.join(file).to_s %>
<% end %>

#{} only works inside double quotes. E.g. "#{file}", but in this case that's not necessary. You can just use file.

like image 87
Mischa Avatar answered Feb 27 '23 17:02

Mischa