Richard M Richard M - 7 months ago 13
Ruby Question

Error passing object to method using send() in Ruby

I'm having a problem using

send()
to call a method while passing said method an object. I receive an
undefined method ``employee_feedback(#<WorkItem:0x000000057cc7c0>)' for WorkItemMailer:Class
error.

This is in my work_item.rb model:

def send_work_item_mail
forms_needing_mail = ["employee", "install", "repair"]
if forms_needing_mail.include?(self.form)
WorkItemMailer.send("#{self.form}_feedback(#{self})").deliver_now
end
end


Which is being called as:

@work_item.send_work_item_mail


in my work_items_controller.rb

And the following is the method in my mailer:

def employee_feedback(work_item)
@work_item = work_item
@employee = User.find_by(id: @work_item.employee)
@manager = User.find_by(id: @employee.manager)
mail to: @manager.email, subject: "Employee feedback for #{@employee.name}"
end


Am I using send incorrectly, or is there something else at play here?

Answer

Calling send on an object is identical as calling a method directly. The difference is that you pass the method name as an argument to send. Subsequent arguments to send, (after the method name) are passed as parameters in the method

So this:

WorkItemMailer.employee_feedback(self)

Should be called as:

WorkItemMailer.send(:employee_feedback, self)

In your case:

WorkItemMailer.send("#{self.form}_feedback", self).deliver_now