开发者

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_ima开发者_StackOverflowge" 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!


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/'


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜