I'm updating this because while the question was answered, nothing related to the title was :) How can I best manage dependencies with CoffeeScript classes?
Let's say I have a Super Class, 'utils.coffee':
fs = require 'fs'
# another bazillion libs
class Utils
doThis: () ->
console.log 'done!'
exports.Utils = Utils
In my Sub Class, I can easily call doThis
. But I can't reference fs
without getting the error: ReferenceError: fs is not defined
. myclass.coffee
:
{Utils} = require './utils.coffee'
class MyClass extends Utils
doThat: () ->
fs.readFile 'any_old_file', (error, fd) =>
buffer = fd.toString()
# do stuff
exports.MyClass = MyClass
Than we run it:
{MyClass} = require('./myclass.coffee')
myclass = new MyClass()
myclass.doThis() # Cool!
myclass.doThat() # Not good
You should not put @
before your trace
method. That makes it a class-level function instead of instance-level, along with all the other methods in that class.
trace: (className, method) ->
I would also recommend that you move your require calls out into the top-level scope, since there is no reason to call require every time your object is instantiated.
Instead of this:
@restler = require('restler')
@_ = require('underscore')
Just put this at the top:
restler = require 'restler'
_ = require 'underscore'
And the better Coffeescript way to do this:
Utils = require('./utils.coffee').Utils
is this:
{Utils} = require './utils.coffee'
Instead of this:
(if (results and results.length > 1) then results[1] else '')
Just do this:
if results?.length > 1 then results[1] else ''
Also I think this:
@buildKey: (args)
should probably be a splat, and could be rewritten like this:
buildKey: (args...)
@debug(@getName(), 'buildKey', "arg: #{arg}") for arg in args
return args.join ':'
I recommend that you familiarize yourself with CoffeeScript scoping rules, because that seems to be the source of most of your issues.
You have @fs = fs
in your Utils
class. This is equivalent to writing Utils.fs = fs;
in JavaScript. Then you try to access this using fs
in your MyClass
class, which makes no sense, since fs is not in scope, as it is attached to Utils.
You would have to do Utils.fs.readFile 'any_old_file', (error, fd) =>
if you want to access the fs
reference you had previously saved.
Only referencing fs
inside of the utils.coffee
file, but outside of Utils
, did not allow me to access it from another file. I had to set it like so:
fs = require 'fs'
# another bazillion libs
class Utils
@fs = fs
doThis: () ->
console.log 'done!'
exports.Utils = Utils
Than, I simply accessed it like:
{Utils} = require './utils.coffee'
class MyClass extends Utils
doThat: () ->
Utils.fs.readFile 'any_old_file', (error, fd) =>
buffer = fd.toString()
# do stuff
exports.MyClass = MyClass