Tuesday, January 08, 2008

Expose Module methods as Instance and Class methods

Have you ever wondered how to include a Module and has its methods be available as instance methods and class methods? I certainly did and after doing a little research I figured out a way to do this in Ruby. For the experience Ruby programmers out there, this is probably very obvious but for those that haven't completely figured out Class object and instance of a class then this should help a little. Or totally confused you.

I don't know whether it is wise to do this but at least it is possible to do. Anyway, enough talking. Here is the code in all it (not so) glory.

module Methods
def self.included(base)
# add methods in ClassMethods into the meta class
base.extend(ClassMethods)
end

def hi
# accessing the meta class to call the
# real method
class << self
self.hi
end
end

def bye
class << self
self.bye
end
end

module ClassMethods
def hi
puts "Hello"
end

def bye
puts "Good Bye"
end
end
end

class Greeting
include Methods
end

# Calling Instance methods here
Greeting.new().hi
Greeting.new().bye

# calling Class methods here
Greeting.hi
Greeting.bye

1 comment:

Offshore Software Development Company said...

I was searching for ruby on rails consultants and landed up onto your column and i ought say thank you for sharing such practical information.