Dynamically creating class methods

S

Shak Shak

I want to create a class method which allows us to create further class
methods, so something like:

class Test
class << self
def create_method(name, proc)
self.class.send:)define_method, name, proc)
end
end
end

proc = lambda {puts 'Hello world'}
Test.create_method:)foo, proc)
Test.foo #want this
Integer.foo #don't want this

The problem with the above is that create_method adds foo to all
classes. self.send on its own doesn't seem to do what I want - it adds
foo as instance method instead.

The method will eventually be placed in an module to be mixed in when
desired, although I don't think that matters here.

Ideas?
 
D

David A. Black

Hi --

I want to create a class method which allows us to create further class
methods, so something like:

class Test
class << self
def create_method(name, proc)
self.class.send:)define_method, name, proc)
end
end
end

proc = lambda {puts 'Hello world'}
Test.create_method:)foo, proc)
Test.foo #want this
Integer.foo #don't want this

The problem with the above is that create_method adds foo to all
classes. self.send on its own doesn't seem to do what I want - it adds
foo as instance method instead.

There are three candidates for the class to which you might send the
:define_method message:

1. Test
2. Class
3. the singleton class of Test

#3 is the one you want. The code you've written sends the message to
Class, and the self.send that you've tried sends it to Test.

Try this:

class Test
def self.create_method(name, proc)
s_class = class << self; self; end
s_class.send:)define_method, name, proc)
end
end

There are other ways (including using class_eval), but that's the
general idea.


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
"Ruby 1.9: What You Need To Know" Envycasts with David A. Black
http://www.envycasts.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top