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.
Having someone else's opinion forced on you? It's Hack Time™!
o =
a: 1
b: 2
c: 3
`with(o) {//`
alert a
`}`
"Compiles" to:
var o;
o = {
a: 1,
b: 2,
c: 3
};
with(o) {//;
alert(a);
};
It's a pity that this is another area where Doug Crockford's opinion is taken as gospel. with
Statement Considered Harmful rejects it on the basis of ambiguity of property writes, but ignores its usefulness when used with a read-only context object, such as a context object which defines a DSL-like API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With