0

If I want to call a class method (mailer method in rails), providing its name in a variable. How can I do that? For objects, we can use send, or we can use read_attribute to read some values

my_object.send("#{self.action_type(self)}")
my_object.read_attribute("#{self.action_type}_email") 

But for class names, nothing is working as send is defined as instance method in object class. I want something like this, which will not work as send can't be applied on class:

Notifier.send("#{self.action_type(self)}").deliver
sawa
  • 165,429
  • 45
  • 277
  • 381
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274

4 Answers4

3

Use eval

eval("Notifier.#{self.action_type}(self).deliver")

Not safe but it should work.

Mohit Jain
  • 43,139
  • 57
  • 169
  • 274
Matzi
  • 13,770
  • 4
  • 33
  • 50
2

You can also do:

method = Notifier.method(action_type)
method.call(self).deliver
Mike Campbell
  • 7,921
  • 2
  • 38
  • 51
2

Classes are objects. There is no difference in how you apply send.

Notifier.send(action_type, self).deliver
sawa
  • 165,429
  • 45
  • 277
  • 381
  • Perfect.. :) Worked like charm – Mohit Jain Mar 05 '13 at 13:28
  • Doesn't this render this question completely worthless? Why did you say in your question that send didn't work on the Class? :/ – Mike Campbell Mar 05 '13 at 13:46
  • @MikeCampbell You don't need to blame the OP for the mistake. Coming to know that classes are objects, and therefore that `send` indeed works on them is a good achievement. – sawa Mar 05 '13 at 14:32
  • I'm not "blaming" the OP, I'm just questioning the value of a question where the accepted answer contradicts the premise of the question. – Mike Campbell Mar 05 '13 at 14:33
0

you can also use

self.class.send(:your_class_method)

AnkitG
  • 6,438
  • 7
  • 44
  • 72