0

In my Rails app I already have the following code:

<% %w(number_of_students edit_class_name tech_help).each do |modal| %>
  <%= render "common/modals/#{modal}" %>
<% end %>

There will be a few more modals added into app/views/common/modals and instead of explicitly listing them out in the %w() I was wanting to loop through the common/modals directory and just render each file.

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

2 Answers2

1

Here is what I came up with:

def render_modals
    files = Dir.glob("#{Rails.root}/app/views/common/modals/*").collect { |file| File.basename(file, ".html.erb").sub("_", "") }.flatten

    files.collect do |modal|
      render partial: "common/modals/#{modal}"
    end.join.html_safe
  end
dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189
0

define a simple method in where is more appropriate (maybe app helper?) like this:

def modals
  %w(number_of_students edit_class_name tech_help)
end

if you need these modals in a controller/model too, maybe you should define this method in an appropriate class? For example

class Modal
  def self.types
    %w(number_of_students edit_class_name tech_help)
  end
end

Also, if you are rendering the templates often, then also define

def render_modals
  modals.map do |modal| # Modals here should be the method that you just defined, example, Modal.types
    render partial: "common/modals/#{modal}"
  end.join
end
fotanus
  • 19,618
  • 13
  • 77
  • 111