best way to dynamically create new instance methods

D

Dan Tenenbaum

Hi, I've been sifting through module_eval, instance_eval, define_method,
and the like and I can't seem to accomplish what I am trying to do,
which is something like this:

class Foo
def initialize
list_of_method_names =
get_list_of_method_names_from_some_external_function
for method_name in list_of_method_names_do
create_method(method_name)
end
end

def create_method(method_name)
# some magic here as yet unknown
end

end

The list retrieval is in initialize() because the list is constantly
changing so I always want the most recent one when I initialize my
class.

What I want create_method() to do (simplified here) is, given the
argument "baz", add a method to the current instance of Foo that would
look like this if it were a traditional method (that is, not dynamically
created):

def baz(*args)
args[0]
end

That seems pretty simple but I have run into all sorts of problems with
various ways of doing it. Rather than recount all those ways and why
they didn't work, I instead present the minimal example of the problem I
am trying to solve and hope that someone can solve it.

Thanks in advance.
Dan
 
J

James Edward Gray II

What I want create_method() to do (simplified here) is, given the
argument "baz", add a method to the current instance of Foo that would
look like this if it were a traditional method (that is, not
dynamically
created):

def baz(*args)
args[0]
end
class Dynamic
def initialize(name)
create_method(name)
end
private
def create_method(name)
class << self; self end.send:)define_method, name) { |*args| args.first }
end
end => nil
foo = Dynamic.new:)foo)=> #<Dynamic:0x71dbd4>
bar = Dynamic.new:)bar)
=> # said:
foo.foo("Hi") => "Hi"
foo.bar("Hi")
=> "Hi"

Hope that helps.

James Edward Gray II
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top