I want to dynamically create instance method of child class through class method of parent class.
class Foo
def self.add_fizz_method &body
# ??? (This is line 3)
end
end
class Bar < Foo
end
Bar.new.fizz #=> nil
class Bar
add_fizz_method do
p "i like turtles"
end
end
Bar.new.fizz #=> "i like turtles"
What to write on line #3?
define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more. A few examples of metaprogramming in Ruby are: Adding a new method to Ruby's native classes or to classes that have been declared beforehand. Using send to invoke a method by name programmatically.
use define_method
like this:
class Foo
def self.add_fizz_method &block
define_method 'fizz', &block
end
end
class Bar < Foo; end
begin
Bar.new.fizz
rescue NoMethodError
puts 'method undefined'
end
Bar.add_fizz_method do
p 'i like turtles'
end
Bar.new.fizz
output:
method undefined
"i like turtles"
define_method 'fizz' do
puts 'fizz'
end
...or accepting a block
define_method 'fizz', &block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With