Mohit Jain
Mohit Jain

Reputation: 43929

How to call class methods which are stored in a variable

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

Upvotes: 0

Views: 272

Answers (4)

Mike Campbell
Mike Campbell

Reputation: 7978

You can also do:

method = Notifier.method(action_type)
method.call(self).deliver

Upvotes: 2

sawa
sawa

Reputation: 168081

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

Notifier.send(action_type, self).deliver

Upvotes: 2

AnkitG
AnkitG

Reputation: 6568

you can also use

self.class.send(:your_class_method)

Upvotes: 0

Matzi
Matzi

Reputation: 13925

Use eval

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

Not safe but it should work.

Upvotes: 3

Related Questions