B Seven
B Seven

Reputation: 45943

How to dynamically create a method on a given class in Ruby?

I know that a method can be created with

class Klass
  define_method foo

How can you create a method and pass the class as a param?

def define_method_for klass, method

Ruby 2.2

Edit: Use case:

I am writing a mocking library. So, I want to mock arbitrary classes and methods.

Upvotes: 1

Views: 860

Answers (3)

sawa
sawa

Reputation: 168071

Either do:

klass.class_eval{define_method(:foo){...}}

or:

klass.instance_eval{define_method(:foo){...}}

Upvotes: 2

Abs
Abs

Reputation: 3962

You can define it like this:

    dynamic_name = "ClassName"
    class = Object.const_set(dynamic_name, Class.new) 
    class.send(:define_method, 'method'){puts 'a'}

The wrapping into a method is straightforward.

Upvotes: 1

Eric Terry
Eric Terry

Reputation: 364

I think this is what you are looking for:

def define_method_for( klass, method, my_proc )
  klass.send( :define_method, method, my_proc )
end

Here is how you would use it:

class Klass
end

my_proc = proc { puts 'foo method called!' }
define_method_for( Klass, :foo, my_proc )

Klass.new.foo
#=> foo method called!

You could also define it like this:

 def define_method_for( klass, method, &block )
   klass.send( :define_method, method, &block )
 end

And use it like this:

 class Klass
 end

 define_method_for( Klass, :foo ) do
   puts 'foo method called!'
 end

 Klass.new.foo
 #=> foo method called!

Upvotes: 4

Related Questions