ruby - Using self in modules -


is there difference between following 2 examples? possible method conflicts in second example because of method names? aren't methods within module automatically "encapsulated" within module?

example 1

module imageutils   def self.preview(image)     #do   end end 

example 2

module imageutils   def preview(image)     #do   end end 

if put class foo within module imageutils, how differ?

the difference first example defines module method called preview, , second example defines mixin method preview.

so if include first module class, you'll able call method on class (whereas calling method on class instance cause error), while including second module class allow call method on class' instances, calling method on class cause

nomethoderror: undefined method preview foo:class 

regarding conflicts basing on same method name in class , module included it. answer question lays in ruby method lookup, following:

  1. methods object's singleton/meta/eigen class
  2. methods prepended modules (ruby 2.0+ feature)
  3. methods object's class
  4. methods included modules
  5. methods class hierarchy (superclass , ancestors)

method lookup stops, when method found.

with prepend mixin method have precedence in method lookup;

with include method defined in class has precedence in method lookup.

so no conflicts possible.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -