Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namespaces in coffeescript

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.

like image 384
Johann Philipp Strathausen Avatar asked Dec 04 '22 21:12

Johann Philipp Strathausen


1 Answers

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.

like image 112
Jonny Buchanan Avatar answered Dec 07 '22 11:12

Jonny Buchanan