Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you limit CoffeeScript (or JavaScript) execution to a particular controller and action in Rails 3.1?

The new Rails 3.1 asset pipeline is really nice, but since all CoffeeScript (or JavaScript) files get melded down into a single file that is included in every page, it raises this question:

How do I limit the execution of my script to a particular controller or action? Is there a way within my CoffeeScript to know which controller and action was used during the request so that I can put conditional statements in my script?

Or am I approaching this the wrong way altogether?

like image 315
adamjcooper Avatar asked May 26 '11 11:05

adamjcooper


People also ask

Does CoffeeScript compile to JavaScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

What is Rails CoffeeScript?

CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, Python and has influenced MoonScript, LiveScript, and JavaScript.


2 Answers

Trevor Burnham answers this question nicely here: How do I associate a CoffeeScript file with a view?

He says:

There are two common approaches:

  1. Make behavior conditional on the presence of a particular element. For instance, code to run a signup sheet should be prefaced with something like

    if $('#signup').length > 0

  2. Make behavior conditional on a class on the body element. You can set the body class using ERB. This is often desirable for stylesheets as well. The code would be something like

    if $('body').hasClass 'user'

And if you're interested in CoffeeScript, Trevor is working on a book that looks to be very good: http://pragprog.com/titles/tbcoffee/coffeescript

like image 78
adamjcooper Avatar answered Oct 20 '22 05:10

adamjcooper


One way to restrict coffeescript to a particular view is to make a custom sprockets file for the javascript in question, similar in format to application.js. Say you call it extras.js.

//= require my_code.js.coffee

Then use javascript_include_tag "extras" to include that code in the views you want, either by making a custom layout for those views, or by using content_for()

BTW, your question stated that the rails pipeline forces you to put all your js assets in one file. That's not true. That's efficient often to avoid multiple round trips, but you can have multiple sprocket files.

like image 34
Alex Blakemore Avatar answered Oct 20 '22 05:10

Alex Blakemore