Skip to content

Instantly share code, notes, and snippets.

@melvynhills
Created April 24, 2012 21:14
Show Gist options
  • Save melvynhills/2483876 to your computer and use it in GitHub Desktop.
Save melvynhills/2483876 to your computer and use it in GitHub Desktop.
Rails image asset paths available in JavaScript
# Full code at https://gist.github.com/1406349/fa7c357b86790c183f3ef81ad6870b78bb2de343
window.assets = {
<%
Dir.glob(Rails.root.join("app/assets/images/**/*.*")).map do |path|
img_name = path.gsub(Rails.root.join("app/assets/images/").to_s, "") %>
"<%= img_name %>": "<%= asset_path(img_name) %>",
<% end %>
}
# Then all images are available as such: window.assets['my_image.jpg']
@jbescoyez
Copy link

I created a little helper for the matter. It does not only look for assets in 1 path but in any path where assets are stored (/lib/assets, /vendor/assets, ...) - even in gems.

  # application_helper.rb
  def asset_paths_to_json(*asset_types)
    asset_types  = [asset_types].flatten.join('|')
    _asset_paths = asset_paths.asset_environment.paths.select{ |path| path =~ /#{asset_types}/ }

    asset_filenames = _asset_paths.map{ |path| asset_paths.asset_environment.entries(path) }.flatten
    asset_array     = asset_filenames.map{ |entry| [entry.to_s, asset_path(entry.to_s)] }

    Hash[asset_array].to_json
  end

Then you can do:

  # In views
  window.assets =  <%= asset_paths_to_json(:images, :javascripts) %> # if you want to map images and JS

Cheers,

JB

@melvynhills
Copy link
Author

Oh great! Exactly what I needed.
I probably wasn't clear with my question then :)

For use within the asset pipeline, we have to import ApplicationHelper:

# assets.coffee.erb
<% environment.context_class.instance_eval { include ApplicationHelper } %>
window.assets = <%= asset_paths_to_json(:images) %>

@jbescoyez
Copy link

I think this will work:

window.assets = <%= ApplicationHelper.asset_paths_to_json(:images) %>

@melvynhills
Copy link
Author

Doesn't work for me.

@jbescoyez
Copy link

You are right. My mistake.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment