Adding methods to an existing class

I’m fumbling over syntax trying to figure out how I could write a method
that adds a method to a given class. I’d call it like this.

addTestMethod(Foo)

where Foo is a class.

addTestMethod would add a fixed “test” method to the class passed to it.

An example would be greatly appreciated!

···

A.G. Edwards & Sons’ outgoing and incoming e-mails are electronically
archived and subject to review and/or disclosure to someone other
than the recipient.


Hi –

I’m fumbling over syntax trying to figure out how I could write a method
that adds a method to a given class. I’d call it like this.

addTestMethod(Foo)

where Foo is a class.

addTestMethod would add a fixed “test” method to the class passed to it.

An example would be greatly appreciated!

def add_test_method(klass)
klass.class_eval {
define_method(:some_test) { puts “testing!” }
}

or: klass.class_eval “def some_test; puts "testing!"; end”

or (1.8.0 only):

klass.class_eval { def some_test; puts “testing!”; end }

end

class A
end

a = A.new
add_test_method(A)
a.some_test # => testing!

(I’ve chosen “some_test” so as not to interfere with Kernel#test.)

David

···

On Thu, 7 Aug 2003, Volkmann, Mark wrote:


David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav