Ruby: How to attach a callback through inheritance

I'm having trouble with Ruby about callbacks (and inheritance). Here is my code:

class Lmao def initialize @str = "HAHAHAHAHAHHAHAHAH" @before_laughing = [] end def self.inherited(base) base.extend(Callbacks) end def laughing @before_laughing.each {|method| send(method) } @str end end module Callbacks def before_laughing(*methods) @before_laughing = methods end end class Lol < Lmao before_laughing :downcase_please def downcase_please @str.downcase! end end a = Lol.new a.laughing # => "HAHAHAHAHAHHAHAHAH" 

And, as you can see, my laugh back call does not work ... because the @before_laughing array is empty. I believe that this can be fixed by editing the method for saving * methods in the Lol instance method (from inside Callbacks). But I really don't see how ...

If you know the solution, thanks for your light!

+4
source share
2 answers

Thanks Mon_Ouie solution:

 class Lmao def initialize @str = "HAHAHAHAHAHHAHAHAH" end def self.inherited(base) base.extend(Callbacks) end def laughing self.class.callbacks_before_laughing.each {|method| send(method) } @str end end module Callbacks def before_laughing(*methods) @before_laughing = methods end def callbacks_before_laughing @before_laughing end end class Lol < Lmao before_laughing :downcase_please def downcase_please @str.downcase! end end 

Pretty awesome.

+3
source

There are two instance variables in the code called @before_laughing : one is an instance variable of the Lmao class, which is initialized to [] (i.e., an empty Array ) in the Lmao initialize instance methods and read in the Lmao laughing instance method. However, since the only place this instance variable is written is the initializer, it will always be an empty Array .

Another instance variable is an instance variable of the object itself of the Lol class, which is set to Array [:downcase_please] inside the before_laughing method. This one, however, is never read.

+1
source

Source: https://habr.com/ru/post/1333740/


All Articles