Rails Against The Machine

Just a mind dump. Why are you even reading this?

Thursday, 3 April 2008

 

Meta programming

First up adding a method to a class.

#example of adding a method to a class
class NoiseMachine; end

def add_gun_to obj
obj.class.class_eval do
def pull_trigger
puts "BANG!"
end
end
end

a=NoiseMachine.new
add_gun_to a
a.pull_trigger


Now to a single object

#example of adding a method to an object 
#this is a so called 'eigenclass' method
b=NoiseMachine.new

def add_button_to o
def o.push_button
puts "beep"
end
end

add_button_to b
b.push_button


Dynamically defining methods

#example of dynamicaly defining a methods
class NoticeBoard
def self.notices(*args)
args.each do |arg|
define_method "i_want_to_"+arg do
puts "You can " + arg.gsub( /_/, ' ') +" in this village"
end
end
end

notices "buy_a_dog", "take_spanish_lessons", "do_baby_yoga"
end

post_office=NoticeBoard.new
post_office.i_want_to_buy_a_dog
post_office.i_want_to_take_spanish_lessons
post_office.i_want_to_do_baby_yoga

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2007   August 2007   September 2007   December 2007   January 2008   February 2008   March 2008   April 2008   June 2008   July 2008   August 2008   October 2008   November 2008   January 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]