How to share code between ruby ​​refinements?

module Ext
  refine Hash do
    def foo
      puts :in_foo
    end
    def bar
      puts :in_bar
      foo
    end
  end
end
module Test
  using Ext
  Hash.new.bar
end
# in_bar
# in_foo
# => nil

This works as expected. But if I want to share fooboth barbetween Hashand Arraywith help include, he fails.

module Shared
  def foo
    puts :in_foo
  end
  def bar
    puts :in_bar
    foo
  end
end
module Ext
  refine Hash do
    include Shared
  end
  refine Array do
    include Shared
  end
end
module Test
  using Ext
  Hash.new.bar
end
# in_bar
# NameError: undefined local variable or method `foo' for {}:Hash

Is there a way to share code between qualifications?

0
source share
1 answer

The problem is not sharing. Get rid of the Arrayrefinement completely and you will get the same behavior.

According to the documentation :

eval, . . , . , , , .

, , refine do ⇒ include. include refine. , , "" .

, refinemenets, ruby ​​( ):

$ref = lambda do
  def foo
    puts :in_foo
  end
  public :foo
  def bar
    puts :in_bar
    foo
  end
  public :bar
end
module Ext
  refine ::Hash do
    $ref.call
  end
end
module Test
  using Ext
  ::Hash.new.bar
end

#⇒ in_bar
#⇒ in_foo
0

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


All Articles