ruby on rails - What's the difference between sending :include to class and directly defining method in second class definition? -
recently had add method redmine's core class. unable use inheritance, i've done this:
require_dependency 'time_entry_query' class timeentryquery < query def my_new_method(foo, bar) end end
and works - method added new objects. however, i've seen declaring new method in own module instead , sending :include class, become mixin. here's example:
module patches module someclasspatch def my_new_method end end
and somewhere in app's initialization:
someclass.send(:include, patches::someclasspatch) unless someclass.include? (patches::someclasspatch)
what's difference between these 2 methods , 1 should use?
there 2 differences:
when use mixin, there clear place "patch" methods can live. if wonder "hmm, where's
my_new_method
" coming from, , at, say,timeentryquery.ancestors
ortimeentryquery.instance_method(:my_new_method).owner
, returnpatches::someclasspatch
. know have file namedlib/patches/some_class_patch.rb
somewhere find defined. (i trysource_location
well, not reliable.)mixing in module class makes module superclass of class being mixed into. so, if there
my_new_method
defined intimeentryquery
, first option overwrite it, whereas in second option, method becomesuper
method of method. iow: second option, new method won't called unless existing method callssuper
.
Comments
Post a Comment