Using self in modules

Is there any difference between the two examples below? Is it possible to get method conflicts in the second example due to method names? Are the methods inside a module automatically "encapsulated" within that 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 put everything in a class Foo

in a module ImageUtils

, how would that be different?

+3


source to share


1 answer


The difference is that the first example defines a module method called preview

and the second example defines a mixin method preview

.

So, if you include the first module in a class, you will be able to call that method in the class (whereas calling the method on the class instance will result in an error), while including the second module in the class will allow you to call the method on the class instances, but calling the method in the class itself will call

NoMethodError: undefined method preview for Foo:Class

      

Regarding conflicts based on the same method name in the class and the module it contains. The answer to this question lies in finding a Ruby method that looks like this:

  • Methods from singleton / meta / custom class
  • Methods from added modules (Ruby 2.0+ feature)
  • Object class methods
  • Methods from included modules
  • Methods from the class hierarchy (superclass and its ancestors)


The method search stops when the method is found.

Using prepend

the mixin method will take precedence in finding methods;

With a method include

defined in a class takes precedence in finding methods.

Thus, no conflicts are possible.

+8


source







All Articles