How should one provide assets in an engine in Rails 3.1? Where should they be located and can they be included automatically?
1 Answers
The paths to the all the engines' assets folders are automatically loaded.
The assets themselves are not loaded by default. This is understandable as the loading is done with require_tree .
, which loads all css/js from the current folder (i.e. the main application assets' folder) but doesn't say anything about the engines assets.
The easy solution is to ask the user to require the js/css in application.js/css or wherever else it is needed. As the paths are loaded correctly, the user only need to specify the name of your asset (I'd recommend using the name of your engine). Example:
Appended to main_app/app/assets/javascripts/application.js
:
//= require your_engine_name
If you have split your js in different files, your file your_engine_name/app/assets/javascripts/your_engine_name.js
could have the following:
//= require_tree .
This will load all js files in your_engine_name/app/assets/javascripts/
, as the "." refers to the local folder (in this case the folder of your engine's javascripts).
Note that ActionView::Helpers::AssetTagHelper.register_javascript_expansion
appears not to have any effect when config.use_sprockets
is set. I hope they'll at least put a warning in that case.
If you have a rake task to install your engine, then you could do the append to application.js.
Another way for the user to include it is to insert <%= javascript_include_tag "your_engine_name" %>
in the erb layout.
I don't think there is a way to have it inserted automatically

- 78,216
- 16
- 166
- 166
-
1The sprockets stuff is currently under going some work, but the rest of what you said is spot-on. Well done. – Ryan Bigg May 04 '11 at 03:51
-
What about images? I tried accessing images from a gem's asset but it failed... Are those two problems related? – mabounassif Aug 19 '11 at 20:19
-
NVM I commented too quickly, the assets within a gem now load automatically in rails 3.1 – mabounassif Aug 19 '11 at 20:28
-
I've created a gem (engine), using rails 3.1.0.rc6. Added some assets to it's app/assets. From the test/dummy application they show on the Rails.application.config.assets.path. But when I require it from bundler in other application Gemfile it doesn't... It doesn't make sense for me, application shows the jquery-rails in assets path but not my gem. Am I missing something here? – Tiago Aug 27 '11 at 22:02
-
1This was very helpful, but with rails 4, (probably all) i had to do a //=require my_engine_name/application.js to get the files included. – bobbdelsol May 29 '14 at 23:40