Reputation: 520
Is there a difference between the following two examples? Is it possible to get method conflicts in the second example because of method names? Aren't methods within a module automatically "encapsulated" within this module?
Example 1
module ImageUtils
def self.preview(image)
#do something
end
end
Example 2
module ImageUtils
def preview(image)
#do something
end
end
If I would put everything into a class Foo
within the module ImageUtils
, how would this differ?
Upvotes: 2
Views: 1068
Reputation: 52357
The difference is that first example defines module method called preview
, and second example defines mixin method preview
.
So that if you include first module into a class, you'll be able to call this method on the class (whereas calling the method on the class instance would cause the error), while including the second module into the class will allow you to call the method on class' instances, but calling the method on the class itself will cause
NoMethodError: undefined method preview for Foo:Class
Regarding conflicts basing on the same method name in class and module included to it. Answer to this question lays in Ruby method lookup, which is following:
Method lookup stops, when the method is found.
With prepend
the mixin method will have precedence in method lookup;
With include
method defined in class has the precedence in method lookup.
So no conflicts are possible.
Upvotes: 8