But what about code isolation through all our sources files ?
CofeeScript respond to that perfectly with creation of one function object per file compiled. To add a global variable, you simply define it for the window object :
call initializers in your layout
I first wrote the gem Epyce to limit code loaded to only current controller and view, but this had 2 main issues :
- loose benefit of one big js file to be put on a CDN
- shared code between views must go to controller .js file
Then I rollback to the big application.js file and add initializers registration to my layout.
Like this for erb:
or if like me you are a haml:
Each initializer function can be binded to severals names.
By convention views are named => controllerName_viewName
here is an example of binding a initializer to the Person controller
Here is an example of binding several views to one initializer
initializers are cumulative
register_init() several times on the same name cumulate initializers
will produce in console:
The registering code
To make all the previous code work, we need to define the Rails object.
Note the usage of
#= require_self to ensure your Rails object will be defined before including all our others files
One more thing
When registered, initializers can be called using init() and there name as string or directly on the Rails object.
Biblio and links