Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript: dynamically create instance of the class a method is called on

I am building a Node.js application using object oriented coffeescript.

I have a super class with a static method like:

class RedisObject
 @find: (id, cb) ->
    client.HGETALL "#{@className()}|#{id}", (err, obj) =>
      unless err
        cb(new RedisObject(obj, false))

There is a subclass like

  class User extends RedisObject

When I call find() on the User class I want it to pass a instance of User instead of RedisObject to the callback function.

I tried to realize this by getting the class name of the actual class the method is called on by using

@constructor.name

and use eval() to generate an instance from it - but the problem is that the subclass will be undefined from within the superclass.

How can I realize the behaviour of getting different types of instances returned by the find method depending on which class it is called on, without having to override it in each subclass?

like image 624
Matthias Avatar asked Jan 05 '13 14:01

Matthias


1 Answers

I'm not an expert in CoffeeScript, but wouldn't this work?

class RedisObject
  whoami: () -> "I am a RedisObject"
  @find: () ->
    new this()

class User extends RedisObject
  whoami: () -> "I am a User"

console.log RedisObject.find().whoami() // -> "I am a RedisObject"
console.log User.find().whoami()        // -> "I am a User"

At least the above test seems to pass.

like image 139
jevakallio Avatar answered Nov 20 '22 13:11

jevakallio