0

How can I dynamically call a method in a module?

module Notification
  def self.send_notification(title, message)
    puts title + message
  end
end

def test(string)
  p string
end

if __FILE__ == $0
  send("test", 'hello from test')
  send("Notification.send_notification", 'hello', 'there') # Error: undefined method `Notification.send' for main:Object (NoMethodError)
end

Edit: I have more than one Module in my library and I really need to be able to convert a string to the module name. Say I also have a Module called Email. Maybe Eval is the only way? Edit2: Renamed method in order not to conflict with built in send-method.

hirolau
  • 13,451
  • 8
  • 35
  • 47

1 Answers1

5

I see the only way, if you wish to get a module by name defined as a String, and don't use the #eval:

Object.const_get( 'Notification' ).send( 'send_notification', 'hello', 'there' )
# hellothere

If you wish to use #eval that is strongly non-recommended in many cases:

eval( 'Notification' ).send( 'send_notification', 'hello', 'there' )
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69