Sometimes you’ll want to refer to your image assets from inside of your JavaScript or CoffeeScript files. We have nice rails helpers that would allow us to do so but we need to append .erb to every .js or .coffee file we want to reference images.

I didn’t like it that way, because ERB inside of CoffeeScript looks odd and having the file end with .erb messes up syntax highlighting.

A way around this is by adding following piece of code (not the beautiful one) to one single file that ends on .erb (i.e. js_assets.js.coffee.erb) and let it provide the helper method we need:

<%
imgs = {}
Dir.chdir("#{Rails.root}/app/assets/images/") do
  imgs = Dir["**"].inject({}) { |h,f| h.merge! f => image_path(f) }
end
%>

window.image_path = (name) ->
  <%= imgs.to_json %>[name]

This adds up all images inside of app/assets/images and makes them available via the global helper method image_path. From there on it’s simply:

icon = image_path('icon.png')

inside of your Javascript or CoffeeScript files and it also works in production as the returned filename contains the digest.

P.S - Dont forget to include that file (js_assets.js.coffee.erb) to applications.js