mixins - What is the difference between 'include' and 'prepend' in Ruby? -


from module

module#append_features(mod) → mod => when module included in another, ruby calls append_features in module, passing receiving module in mod. ruby’s default implementation to add constants, methods, , module variables of module mod if module has not been added mod or 1 of ancestors.

module#prepend_features(mod) → mod => when module prepended in another, ruby calls prepend_features in module, passing receiving module in mod. ruby’s default implementation to overlay constants, methods, , module variables of module mod if module has not been added mod or 1 of ancestors.

can me understand below questions:

  • what more features of module defined append , prepend except default?

  • how differ functionally?

  • when use append_features , when prepend_features?

  • what difference between 2 bold lines above?

  • what features of module defined append , prepend?

as specified in text quoted:

the constants, methods, , module variables

  • how differ functionally?

both add methods of mixed-in module passed module (class). difference in lookup order of these methods, in case target class has them defined:

include behaves if target class inherited mixed-in module:

module foobar   def     puts "2 - module"   end end  class foo   include foobar    def     puts "1 - implementing class"     super   end end  foo.new.say # =>             # 1 - implementing class             # 2 - module 

prepend makes methods mixed in module "stronger" , executes them first:

module foobar   def     puts "2 - module"     super   end end  class foo   prepend foobar    def     puts "1 - implementing class"   end end  foo.new.say # =>             # 2 - module             # 1 - implementing class 

the example kindly ripped off here: http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html

  • when use append_features , when prepend_features?

use prepend when want keep methods of target module (class) @ end of method lookup chain.

some real-world examples can found searching ruby, module , prepend:

(note: mentioning methods, easiest picture when comes inheritance , mixing-in, same applies other features.)


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -