0

There are several ways to include controller-specific assets in Rails:

One option which is not DRY is to add = yield :head in the layout and content_for(:head) { ... } in every top-level view. If an asset is controller-specific, it should be specified only once per controller, not in each view. Of course, this approach is awesome for view-specific assets.

A second option which is not declarative is to add an asset corresponding to the controller name if it exists. Instead of checking whether something exists, I should simply say (where appropriate) that it exists and must be included. Also, I'm not sure if the response would be cached to avoid a runtime performance hit. On the positive side, this approach wouldn't require any changes to views or controllers, but it might open up the possibility for name clashes, especially with legacy models.

A third option is to include all assets of a type in a single file. Browsers shouldn't download assets they don't need, and this would make it more difficult to debug the application. This option would be fine if the total asset size is still manageable.

Is there some way to declaratively include a single controller-specific asset in a separate file in a DRY way without breaking the MVC model using very little code?

Community
  • 1
  • 1
l0b0
  • 55,365
  • 30
  • 138
  • 223

1 Answers1

0

Rails will serve only the code in the controller specific asset files to the specified controller if you use the following include commands in your application layout:

<%= javascript_include_tag params[:controller] %>
<%= stylesheet_link_tag params[:controller] %>

I suspect if you do this you will need to also do the following:

  • Still include the <%= javascript_include_tag :application %> and <%= stylesheet_link_tag :application %> to get all your cross controller assets
  • Check how the require_tree . directives work to ensure that the controller specific assets are not being loaded both by the application.css and the <%= stylesheet_link_tag params[:controller] %> in fact you may need to remove the require_tree . and load any cross controller sheets directly into the application files

See the Rails Guide on the Asset Pipeline in section 2 for more information.

nmott
  • 9,454
  • 3
  • 45
  • 34