2

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

kcdragon
  • 1,724
  • 1
  • 14
  • 23
Giorgio Robino
  • 2,148
  • 6
  • 38
  • 59
  • 1
    Such a method is not meant to be called. Either include the module somewhere or look at http://apidock.com/ruby/Module/module_function – Pascal Aug 28 '16 at 16:18

1 Answers1

3

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.

kcdragon
  • 1,724
  • 1
  • 14
  • 23