Friday, December 5, 2008

Ruby Metaprogramming

Define a metaclass


class Object
def metaclass; class << self; self; end; end
end

Rails style of extending class and instance methods(also available as a textmate snippet mod ->)

module ModuleName
module ClassMethods
end

module InstanceMethods
end

def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end

Resources:
Seeing Metaclasses Clearly
Metaprogramming by Dave Thomas
Dynamically Created Methods In Ruby
Ruby Metaprogramming techniques
Eval options in ruby