RSG
RSG

Reputation: 7123

Rendering images in a directory

Greetings. I'm pretty sure there's a cleaner way to do this, but I can't find it.

I have a directory of icons users can pick to include in their content. I have a partial to create the palette of icons for them to choose from:

<% @files = Dir['public/images/prompts/*.*'] %>
<input type="hidden" id="test_prompt_image" value="/images/prompts/default.png" />
<% @files.each do |f| %>
    <div onclick="$('#test_prompt_image').val('<%= f.gsub("public","") %>')" class="MultiColumn">
      <img src="<%= f.gsub("public","") %>"/>
    </div>
<% end %>

The results returned by the Dir include the full relative path on the server "public/images/...", but I have to remove "public" for the src path to find the image. Is there a call to use instead of Dir that returns a URI? I also messed around with including RAILS_ROOT in the directory path, but that just gave me a longer file path to clean into a request path.

Thanks!

Upvotes: 2

Views: 1332

Answers (2)

Dogweather
Dogweather

Reputation: 16819

By the way, to do things the Rails way (and good architecture), move the line:

@files = Dir['public/images/prompts/*.*'].map {|f| f.sub('public','') }

...out of the view and into the controller. The controller is the place to set up the variables and do data storage access, and the view is the place to display and format the info. And further, I would refactor this more by creating a constant for that path, e.g. in environment.rb:

ICON_DIRECTORY_PATH = 'public/images/prompts/'

Upvotes: 2

Aaron Hinni
Aaron Hinni

Reputation: 14736

Just do the removing of the public when you grab the list of files...

@files = Dir['public/images/prompts/*.*'].map {|f| f.sub('public','') }

Upvotes: 1

Related Questions