We’re using Rails 3.0 and I have a js.erb file which contains hard-coded paths for our logo images, but this means we can’t easily add more logos to the application once it’s deployed. Ideally, we would like to find the names of every image in a directory so users can just throw some images in the folder to add more logos.
I tried this code, http://pragprog.com/wikis/wiki/InstantGratification-2/version/21 which boils down to using ruby to send the list to an html.erb. However, since this is a js.erb and is located in our app/assets/javascripts folder, I don’t know how to get ruby variables from a controller to the js.erb.
I also briefly tried importing System.IO in the js.erb to access some file APIs. Didn’t work and I’m not very used to working with erb files.
You are right that the js.erb file won’t have direct access to a controller’s methods in the same way that a normal html.erb action view would have. You can embed the file listing logic in you js.erb directly because you can reference Ruby core library, e.g. this snippet will output the names of the files in the app/assets/images directory as a JavaScript array:
Or you could implement a helper method in a helper class, e.g.
and then you have to include it in your js.erb as follows: