0

I would like to loop over a directory of .png icons and add them to a on a standalone page. I would also like to expose the file name of the .png under each one.

In a nutshell, this should become an automated feature to display all icons I'm currently using in my development environment so I can use this standalone page as an icon directory.

I'm very new to Ruby but my question first led to me this article but does not go far enough: Iterate through every file in one directory

My (basic inline HTML), attempt so far:

<ul>

    <% Dir.glob('/assets/css/img/png/*.png') do |icon| %>

        <li> <%= "#{icon}" %> </li>

    <% end %>

</ul>

Any help is hugely appreciated.

Community
  • 1
  • 1
Padwah
  • 3
  • 3
  • 3
    What problem are you having with the code? – wavemode Apr 08 '15 at 16:51
  • It looks like you are interpolating the variable icon. Is there a particular reason why |icon| would need to be in quotes? Isn't it an image? What kind of error are you getting? If you are just seeing a bunch of text on your html, there is a good chance I would assume that it is returning the icon-path to your html, as opposed to an actual image. Can we see the error you are getting so we have a little more information to find out whats going on? – James Apr 08 '15 at 22:34
  • @wavemode - My code is not producing any results at all ! I'm sorry for not being able to give a better platform to work off. – Padwah Apr 09 '15 at 09:26

2 Answers2

1

I'm not an expert so any improvements would be appreciated. I could only get the Ruby Dir.glob() to iterate by providing the absolute path to the directory. I'm using Rails 4.0.8. Here's what works for me:

<ul>
  <% Dir.glob("#{Rails.root}/app/assets/images/*.png") do |icon| %>
      <% icon_base = File.basename(icon) %>
      <li><%= link_to icon_base, image_url(icon_base) %></li>
  <% end %>
</ul>

This produces a list of hyperlinks to all PNG images in /assets/images.

StuffAndThings
  • 341
  • 1
  • 8
  • Thank you for your help but unfortunately I'm not using Ruby on Rails - just plain old Ruby for me. – Padwah Apr 09 '15 at 09:29
  • Sorry for my confusion, though I would still like to help. Could you please provide additional context about your running environment? What gems are you using? Are you running a web server, or just opening the html on your browser? What is your process for rendering the embedded ruby? – StuffAndThings Apr 09 '15 at 15:37
0

You are giving an absolute path to Dir.glob so it will not be relative to your Rails project directory.

Try prepending the Rails root path to get a valid absolute path.

Dir.glob(Rails.root + "/assets... etc

Kent Dahl
  • 166
  • 4