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:
- methods object's singleton/meta/eigen class
- methods prepended modules (ruby 2.0+ feature)
- methods object's class
- methods included modules
- 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
Post a Comment