0

I have a method that sends a message when it triggers something. The signature is:

Sender.send(user, message_id, source)

The usage scenario is in the callbacks in active model. When some model is verified, we send a message through the template:

after_save if: 'verified_changed? && verified' do
    Sender.send(user, :verified, self) # pass self as the template parameter
end

We pass self. There are some solutions to make invoking simple as below:

after_save if: 'verified_changed? && verified' do
    Sender.send(user, :verified) # not need to pass self, guess it when invoking
end

Is there a method that passes self when a method is invoked?

More concrete examples are below:

#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>

I share my send method below (In class 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
sawa
  • 165,429
  • 45
  • 277
  • 381
Run
  • 876
  • 6
  • 21
  • 1
    yes we can achieve this by implementing method with default params change `send` method definition like `def send(user, verified, obj=self)`. Share your send method code then i can give a proper answer below. – Muhammad Ali Apr 01 '16 at 12:09
  • 1
    @MuhammadYawarAli: try this. `self` will not be the caller's `self`. – Sergio Tulentsev Apr 01 '16 at 12:22
  • I think the default self argument is a perfect solution. Thank you all. However, it seems a subtle place in my method declaration. – Run Apr 01 '16 at 12:27
  • @Run: I kinda doubt that this approach will work for you. `self` there will be `Caller`, not whatever you actually wanted. http://pastie.org/10781838 – Sergio Tulentsev Apr 01 '16 at 12:29
  • 1
    Possible duplicate: http://stackoverflow.com/questions/2703136/any-way-to-determine-which-object-called-a-method – Reinstate Monica -- notmaynard Apr 01 '16 at 14:28
  • In object oriented programming, the method execution should be independed of the caller. So if you want to pass self, you should just do it explicitly. As bonus, it is easier to test. – Meier Apr 01 '16 at 16:27
  • Maybe there are some changes in ruby 2.3, the output is not the expected one. – Run Apr 07 '16 at 07:15

0 Answers0