ruby on rails - Check if method defined on mixee class? -
we have module handle canceling models. it's clean, works nice, we've run in issue class want mix in has our module methods (cancel!
, etc) defined.
we tried come new names avoid collisions, seems less-than-ideal, , cleanness of calling cancel!
. so, we've decided want like:
def cancel! cancelly_stuff if class.parent.respond_to(:cancel!) super end
however, it's module, class we're mixing in not class.parent
. unable google how reference mixee-class of module.
i come answer post, using prepend
instead of include
(only ruby 2.x). first including @ top of ancestry chain, since second goes after class.
let see how works @ irb console:
~/rails/learn/ruby (main) > module ~/rails/learn/ruby (main) | def cancel! ~/rails/learn/ruby (main) | puts 'cancel m:a' ~/rails/learn/ruby (main) | super if defined? super ~/rails/learn/ruby (main) | end ~/rails/learn/ruby (main) | end => :cancel! ~/rails/learn/ruby (main) > class c ~/rails/learn/ruby (main) | prepend ~/rails/learn/ruby (main) | def cancel! ~/rails/learn/ruby (main) | puts 'cancel c:c' ~/rails/learn/ruby (main) | end ~/rails/learn/ruby (main) | end => :cancel! ~/rails/learn/ruby (main) > c.ancestors => [ [0] #<class:0x000000035421f0>::a, [1] #<class:0x000000035421f0>::c < object, [2] object < basicobject, [3] pp::objectmixin, [4] kernel, [5] basicobject ] ~/rails/learn/ruby (main) > c.new.cancel! cancel m:a cancel c:c => nil ~/rails/learn/ruby (main) > class d ~/rails/learn/ruby (main) | include ~/rails/learn/ruby (main) | def cancel! ~/rails/learn/ruby (main) | puts 'cancel c:d' ~/rails/learn/ruby (main) | super if defined? super ~/rails/learn/ruby (main) | end ~/rails/learn/ruby (main) | end => :cancel! ~/rails/learn/ruby (main) > d.ancestors => [ [0] #<class:0x000000035421f0>::d < object, [1] #<class:0x000000035421f0>::a, [2] object < basicobject, [3] pp::objectmixin, [4] kernel, [5] basicobject ] ~/rails/learn/ruby (main) > d.new.cancel! cancel c:d cancel m:a => nil
i hope helps issue.
Comments
Post a Comment