ruby-on-rails-3coffeescriptspine.js

Coffeescript - inherit parent class from different coffeescript file


I am creating a spine-rails application and have 2 coffeescript files in lib folder. I wanted to inherit a parent class in another coffeescript file but unable to do so.

#= require coffeescript_file_1

Above statement finds the target coffeescript file but cannot find the parent class.

I found this utlity: https://github.com/fairfieldt/coffeescript-concat

Just wanted to know if using it would be the correct way to find a parent class in a coffeescript file inside another file in a rails app.

I'm not using npm.


Solution

  • You need to "export" the class. CoffeeScript uses an IIFE wrapper to avoid polluting the scope.

    in your application.js :

    #= require coffee_parent
    #= require coffee_child
    

    in your coffee_parent.js.coffee :

    @Parent = class Parent
      doStuff: ->
    

    in your coffee_child.js.coffee :

    @Child = class Child extends @Parent
      doStuff: -> super 1