xotix
xotix

Reputation: 520

Using self in modules

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

Answers (1)

Andrey Deineko
Andrey Deineko

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:

  1. Methods from the object's singleton/meta/eigen class
  2. Methods from prepended modules (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its ancestors)

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

Related Questions