I’d like to use namespaces as one would in javascript by using the keyword “with”, but CoffeeScript reports this as a reserved keyword and refuses to compile is there any way I could use namespaces in cs?
In particular, I want to include a CoffeeScript file dynamically (trusted source), like loading models for a database schema, but I want the included script to have access to a local namespace.
Edit:
Here’s what I want to do. I am setting up a web framework that maps the directory tree to an application based on express and mongoose. For example, there’s a sub-directory ‘models’ that contains a file ‘user.coffee’ with code like this inside:
name:
type: String
unique: on
profiles: [ Profile ]
Whereby Profile is a class that sits in a local object named model. When the user model is being loaded, I wanted it to access the model classes that sit in my local model store.
My work-around for now was to write model.Profile into the file ‘user.coffee’. Hope it is clear what I mean.
2nd Edit
Here’s how I did it without using with:
user.coffee
name:
type: String
unique: on
profiles: [ @profile ]
profile.coffee
content: String
And here’s how it’s dynamically loaded:
for fm in fs.readdirSync "#{base}/models"
m = path.basename fm, '.coffee'
schema[m] = (()->
new Schema coffee.eval (
fs.readFileSync "#{base}/models/#{fm}", 'utf8'
), bare: on
).call model
mongoose.model m, schema[m]
model[m] = mongoose.model m
Seems an okay solution to me.
The Coco fork of CoffeeScript supports a
withsyntax; see https://github.com/satyr/coco/wiki/additions. However, that syntax simply sets the value ofthisto the target object in a block, rather than compiling to the problematic and deprecatedwithkeyword.Let’s say that you wanted to emulate Coco’s
withsyntax in CoffeeScript. You’d do something like this:Then you could write
Of course, in such simple cases, it’s better to use a utility function like jQuery or Underscore’s
extend: