Created
          April 24, 2012 21:14 
        
      - 
      
- 
        Save melvynhills/2483876 to your computer and use it in GitHub Desktop. 
    Rails image asset paths available in JavaScript
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # 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'] | 
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) %>I think this will work:
window.assets = <%= ApplicationHelper.asset_paths_to_json(:images) %>Doesn't work for me.
You are right. My mistake.
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
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.
Then you can do:
Cheers,
JB