Dluks Dluks - 7 months ago 10
Ruby Question

Listing images in a directory with helper using `Dir.glob` and `each ... do` not working

My goal is to be able to include a helper method in my Rails 4 project that will list all images in a particular directory in a view so that I don't have to manually add

image_tags
each time I add a new image.

I've come across several examples of this, but for my purposes I'd like to allocate this job to a helper method, and I can't for the life of me understand why this isn't working.

myapp_helper.rb

module MyAppHelper
def list_logos(clss)
logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
logos.each do |logo|
content_tag("li", class: clss) do
image_tag logo.gsub("engines/myapp/app/assets/images/", "")
end
end
end
end


show.html.erb

<%= list_logos("companies__company") %>


This just prints out the
Dir.glob
array. Before, I had tried
image_tag("myapp/logos/#{image.split('/').last}"
to no avail, and so I thought I might have better luck with the
gsub
method. Nope.

Funny thing is, if, in my helper method, I just write:

logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
image_tag logos.sample.gsub("engines/petitions/app/assets/images/", "")


the image renders fine, which leads me to believe that it's the
logos.each
iteration which is failing.

I'm stumped. I'll add that this is an engines-based project that I've inherited, and I'm a relative newbie when it comes to Ruby and Rails, so I very well could be missing something simple. Yay! Thanks in advance.

Answer

You need to concatenate and return the tags. Try something like this:

module MyAppHelper
  def list_logos(clss)
    logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
    logos.map do |logo|
      content_tag("li", class: clss) do
        image_tag logo.gsub("engines/myapp/app/assets/images/", "")
      end
    end.join
  end
end

Also, since you're constructing HTML in the helper, you'll need to use html_safe in the template:

<%= list_logos("companies__company").html_safe %>

Oh, and the reason you saw the result of Dir.glob is that each returns the object it's called on.

Comments