Why do Ruby refinements only change classes, not modules?

Ruby docs on clarifications :

Refinements change only classes, not modules, so the argument must be a class.

Why is this?

You can neutralize the module:

module MyModule
  def my_method
    "hello"
  end
end

include MyModule
puts my_method # => hello

module MyModule
  def my_method
    "goodbye"
  end
end

puts my_method # => goodbye

I'm sure this is not a good idea, but it might not be so bad if you can limit the scope of such a patch of monkeys. So why can't you?

+4
source share
2 answers

refine Ruby is designed to solve monkey repair and inheritance issues, where it is intended to restrict a monkey patch to class instances within a specific namespace.

, ( ) mixins.

, , .

:

module MyModule
  def my_method
    "hello"
  end
end

include MyModule

puts my_method
# => hello

module MyOtherModule
  extend MyModule

  puts my_method # will print: hello

  def my_method
    "goodbye"
  end
  extend self

  puts my_method # will print: goodbye
end
# => hello
# => goodbye

puts my_method
# => hello

, "monkey-patch" MyOtherModule refine.

MyModule (MyModule ), .

, , , , ... , refine.

0

, . ,

module Foobar
  refine Enumerable
    def all_zero?; all? &:zero? end
  end
end

, :

module Enumerable
  def all_zero?; all? &:zero? end
end

, .

+1

Source: https://habr.com/ru/post/1611213/


All Articles