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?
Trevor Burnham answers this question nicely here: How do I associate a CoffeeScript file with a view?
There are two common approaches:
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
Make behavior conditional on a class on the
bodyelement. 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
//= require my_code.js.coffee
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.
If you are using the gon gem for your vars in coffee script you can use this pattern:
Put a flag for every action in the controller:
def index @gps_coords = GpsCoord.all # Flag for the CoffeeScript to decide which part to run gon.index = true; end def show @gps_coord = GpsCoord.find(params[:id]) gon.lat = @gps_coord.latitude gon.lon = @gps_coord.longitude gon.show = true; end
In the correlating coffee script use those flags to distiguish between the both actions:
# index action? if gon.index? first_coord = gon.gps_coords map.setView([first_coord.latitude, first_coord.longitude], 15); # show action? if gon.show? map.setView([gon.lat, gon.lon], 15);
©2020 All rights reserved.