Friday, February 19, 2010

Meta-programming in Ruby and JavaScript

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:

1. Defer class from a variable.

// JavaScript
var klass = "Person";
p = new window[klass]; //class without namespace
p = new yoolk[klass]; //class with namespace


# Ruby
klass = "Person"
p = Object.const_get(klass).new #class without namespace
p = Yoolk.const_get(klass).new #class with namespace

2. Access class method from instance object

// JavaScript
var p = new Person();
p.constructor.getCount();


#Ruby
p = Person.new
p.class.count

3. Define method of an object

//JavaScript
var p = new Person();
p.hello = function() {
alert('hello');
};


//Ruby
p = Person.new
def p.hello
puts "hello"
end

4. Define class methods

//JavaScript
Person.hello = function() {
alert('hello');
};


//Ruby
def Person.hello
puts "hello"
end

3 comments:

Anonymous said...

Good fill someone in on and this enter helped me alot in my college assignement. Say thank you you on your information.

Anonymous said...

Correctly your article helped me terribly much in my college assignment. Hats afar to you enter, will look progressive for more interdependent articles soon as its united of my favourite issue to read.

fundoo said...

Thanks for the information, we will add this story to our blog, as we have a audience in this sector that loves reading like this” web development

Subscribe in a Reader