Reputation: 45943
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
Reputation: 168071
Either do:
klass.class_eval{define_method(:foo){...}}
or:
klass.instance_eval{define_method(:foo){...}}
Upvotes: 2
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
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