Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create instance methods at runtime?

[ruby 1.8]

Assume I have:

dummy "string" do
    puts "thing" 
end

Now, this is a call to a method which has as input arguments one string and one block. Nice.

Now assume I can have a lot of similar calls (different method names, same arguments). Example:

otherdummy "string" do
    puts "thing"
end

Now because they do the same thing, and they can be hundreds, I don't want create an instance method for each one in the wanted class. I would like rather find a smart way to define the method dynamically at runtime based on a general rule.

Is that possible? Which techniques are commonly used?

Thanks

like image 937
Emiliano Poggi Avatar asked Jul 28 '11 15:07

Emiliano Poggi


1 Answers

use define_method:

class Bar 
end

bar_obj = Bar.new

class << bar_obj
 define_method :new_dynamic_method do
  puts "content goes here"
 end
end

bar_obj.new_dynamic_method

Output:

content goes here
like image 59
ksht Avatar answered Oct 13 '22 22:10

ksht