Chamnap Chhorn

Ruby, Rails, and JavaScript Developer

Meta-programming in Ruby and JavaScript

| Comments

Recently, I have been working with writing a ruby gem, Yoolk API Gem. What is really interesting for me is I do some meta programming and object-oriented programming in Ruby which I have never experienced before. A few month later, there is a requirement that my team needs to write in JavaScript, but I don’t want to touch JavaScript really much. Therefore, my team member took over this task. Whenever I write code in Ruby, I just try to think how to do it in JavaScript as well. Several things that came up to my mind with some from my team member:

  • Defer class from a variable
1
2
3
    var klass = "Person";
    p = new window[klass]; //class without namespace
    p = new yoolk[klass]; //class with namespace
1
2
3
    klass = "Person"
    p = Object.const_get(klass).new #class without namespace
    p = Yoolk.const_get(klass).new #class with namespace
  • Access class method from instance object
1
2
    var p = new Person();
    p.constructor.getCount();
1
2
    p = Person.new
    p.class.count
  • Define method of an object
1
2
3
4
    var p = new Person();
    p.hello = function() {
      alert('hello');
    };
1
2
3
4
    p = Person.new
    def p.hello
      puts "hello"
    end
  • Define class methods
1
2
3
    Person.hello = function() {
      alert('hello');
    };
1
2
3
    def Person.hello
      puts "hello"
    end

Comments