Giorgio Robino Giorgio Robino - 3 months ago 10
Ruby Question

How to call a method with dynamic dispatch (when method is part of a Module), in Ruby?

In Ruby language, I have to call dynamically a method that belong to a Module, having method name as a stored string (say:

"ModuleName::Submodule:methodName"
)

Let's consider this case:

module Dialogs
def paperino(param)
puts "paperino. param: #{param}"
end
end


How can I do .call( "parametro") in run-time ?

I explain better:

In case the method is part of a class I know how to do:
I Instantiate the class (from the string and I call the method object):

class Dialogo
def pluto(param)
puts "pluto. param: #{param}"
end
end

class_name = "Dialogo"
# create class symbol from a string
class_symbol = Kernel.const_get(class_name)

# return a new instance
class_instance = class_symbol.new

# Instantiating a method object
method_object = class_instance.method(:pluto)

# call the method in run time:
method_object.call "parametro_pluto"


And the simpler situation of a method without an explicit class

def pippo(param)
puts "pippo. param: #{param}"
end

method_object = Kernel.method(:pippo)
method_object.call "parametro"


But what is the syntax to call dynamically a method that is part of a Module?

In the following example:

module Dialogs
def paperino(param)
puts "paperino. param: #{param}"
end
end


the method I wish to call is "Dialogs::paperino"

BTW, I don't want to use neither send() or eval(), but just a call().

thanks
giorgio

Answer

I don't think you can. Methods defined in that way on a Module are not meant to be accessed directly.

Dialogs.paperino('a')
NoMethodError: undefined method `paperino' for Dialogs:Module

You could define it on Dialogs using self

def self.paperino(param)

And then you will be able to access it with method

Dialogs.method(:paperino)

If you need to define it as def paperino(param) here is a way you could access the method.

method = (Object.new.extend(Dialogs)).method(:paperino)
method.call('foo')

This defines a new object and then extends that object with the module Dialogs. Then you can get the method.