I've been thinking about CoffeeScript lately, and I just upgraded a Rails project I've been working on to Rails 3.2.8 (from Rails 3.0.9 which didn't have the asset pipeline) following this guide.
I had to do some hackish stuff to get things to work properly. I'm testing out a new page, '/pages/game' and so it has some example CoffeeScript in the the asset directory.
(app/assets/javascripts/page.js.coffee)
class MyObject
constructor: ->
hello: -> alert 'hello world of coffeescript!'
a = new MyObject
a.hello()
Then I added a line to my production environment: (config/environments/production.rb)
config.assets.precompile += %w( pages.js ) # this is needed to precompile coffee script files... it is difficult to understand how manifest files work...
Then typing
$ bundle exec rake assets:precompile
Worked to compile page.js The only problem is that the class I created with CoffeeScript doesn't work exactly as I anticipated. So I opened up my developer console in FireFox and attempted to instantiate the class manually, but it acted like there was no such object named MyClass.
So where have I gone wrong? Was it presumptuous of me to assume I could manually instantiate classes I've written in CoffeeScript? Was my hackish means of adding pages.js to the precompile array inappropriate? If you're a CoffeeScript pro, how would you test your classes and such?
Update: Part of my problem was the 'variable privacy' that is inherant in coffee script classes. This privacy can be implemented in standard javascript, and should be understood before dabbling too far into coffee script. http://benalman.com/news/2010/11/immediately-invoked-function-expression/
That said, the coffee script class needed to be attached to the window object to make it globally accessible, like so:
Corrected
class MyObject
constructor: ->
hello: -> alert 'hello world of coffeescript!'
window.MyObject = MyObject;
Once the class is published in this manor (by attaching it to window as a global) it can be instantiated via a = new MyObject() and then have its function called normally to alert to the screen a.hello()
pages.jsto your precompiled assets. Rather, you should have added it to your JS manifest file via//= require pages. Simply adding it to the precompiled assets doesn't include it in your page.