in my app I have one controller supporting a quite complex object that has a lot of javascript, written in coffescript.
I would like to arrange the javascript on several separate files so to have the code arranged more nicely, although I can't figure out how to import these extra files.
for example I have the file app/assets/javascripts/general_functions.js.coffee
containing the following:
# rounds a number
roundNumber = (rnum, rlength = 5) ->
pow = Math.pow( 10, rlength )
newnumber = Math.round(rnum*pow)/pow
parseFloat(newnumber)
# floors a number
floorNumber = (rnum, rlength = 5) ->
pow = Math.pow( 10, rlength )
newnumber = Math.floor(rnum*pow)/pow
parseFloat(newnumber)
# returns true if the str ends with suffix
endsWith = (str, suffix) ->
str.indexOf(suffix, str.length - suffix.length) != -1
# returns the absolute value of a number (always >= 0)
abs = (num) ->
if num < 0 then - num else num
How do I import it in my app/assets/javascripts/projects.js.coffee
that needs these functions?
I've tried with adding
//= require general_functions
to app/assets/javascripts/application.js
, with no success
any ideas?
thanks,
Javascript should be automatically included in your rails application, every controller has its own js file. Using the instructions below will include them.
Your
app/assets/javascripts/application.js.coffee
should have this line included:Or
app/assets/javascripts/application.js
(plain javascript):When you are viewing your page's source in your browser you should see something like:
What you are describing is a helper or more global js file with generic features. You could add these to the application.js. Moreover, using a structure like below will include vendor/assets/javascripts/some_generic_feature.js(.coffee)
By no success I'm guessing that the browser is telling you that none of your
general_functions.js.coffee
functions exist and you're getting errors like:You have a simple scoping issue. The compiled version of CoffeeScript files are wrapped in a self-executing function to prevent namespace pollution so this:
looks like this when it gets to the browser:
and all the functions you've defined are hidden. If you want your functions to be global, then define them as
window
properties:Or better, you can create an application-specific namespace somewhere before the main (Coffee|Java)Script is loaded:
and put your functions in there:
In
application.js
add both files in the correct order:application.js
Hope this helps!