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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.