我有一个方法可以在触发某些内容时发送消息。签名是:
Sender.send(user, message_id, source)
使用场景位于活动模型的回调中。验证某些模型后,我们会通过模板发送消息:
after_save if: 'verified_changed? && verified' do
Sender.send(user, :verified, self) # pass self as the template parameter
end
我们通过self
。有一些解决方案可以简单地调用,如下所示:
after_save if: 'verified_changed? && verified' do
Sender.send(user, :verified) # not need to pass self, guess it when invoking
end
调用方法时是否有方法传递self
?
更具体的例子如下:
#define a method, return the environment self
def guess
end
guess #=> main
class A
guess #=> A
def a
guess
end
end
A.new.a #=> #<A:0x000000026cd2f0>
我在下面分享我的发送方法(在课程Sender
中):
def send(*users, id, source = self)
desc = source.class.to_s
text = "There is a new process in your #{desc}: #{id}"
users.reject{|user| user.nil?}.each do |user|
send_message(user, tag: 'Process', text: text)
send_mail(user, subject: text, text: text)
send_sms(user, text: text)
end
end