Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 asset pipeline: how to load controller-specific scripts?

If I generate a new controller in Rails 3.1, also a javascript file with the name of the controller will added automatically. Firstly, I thought this javascript file will used only, when the related controller is called.

By default there is the instruction //= require_tree . in the application.js-file, that include every javascript file on it's tree.

How could I load only the controller specific script?

like image 784
Mike Bevz Avatar asked Jul 04 '11 12:07

Mike Bevz


3 Answers

To load only the necessary name_of_the_js_file.js file:

  1. remove the //=require_tree from application.js

  2. keep your js file (that you want to load when a specific page is loaded) in the asset pipeline

  3. add a helper in application_helper.rb

    def javascript(*files)
      content_for(:head) { javascript_include_tag(*files) }
    end
    
  4. yield into your layout:

    <%= yield(:head) %>
    
  5. add this in your view file:

    <% javascript 'name_of_the_js_file' %>
    

Then it should be ok

like image 180
Nguyen Chien Cong Avatar answered Oct 25 '22 09:10

Nguyen Chien Cong


An elegant solution for this is to require controller_name in your javascript_include_tag

see http://apidock.com/rails/ActionController/Metal/controller_name/class

<%= javascript_include_tag "application", controller_name %>

controller_name.js will be loaded and is in the asset also, so you can require other files from here.

Example, rendering cars#index will give

<%= javascript_include_tag "application", "cars" %>

where cars.js can contain

//= require wheel
//= require tyre

Enjoy !

like image 30
albandiguer Avatar answered Oct 25 '22 09:10

albandiguer


I always include this inside my layout files. It can scope your js to action

<%= javascript_include_tag params[:controller] if AppName::Application.assets.find_asset("#{params[:controller]}.js") %>
<%= javascript_include_tag "#{params[:controller]}_#{params[:action]}"  if AppName::Application.assets.find_asset("#{params[:controller]}_#{params[:action]}.js") %>
like image 28
Le Duc Duy Avatar answered Oct 25 '22 09:10

Le Duc Duy