Better way to turn a ruby class into a module than using refinements?

后端 未结 2 1075
春和景丽
春和景丽 2021-01-31 09:39

Module#refine method takes a class and a block and returns a refinement module, so I thought I could define:

class Class
  def include_refined(klass)
    _refine         


        
2条回答
  •  甜味超标
    2021-01-31 10:29

    I am happy indeed with Ruby 2.1 (and later) class-level "private" scope of refinements. My example above can be rephrased as:

    # spec/modulify_spec.rb
    module Modulify
      refine(Class) do
        def include_refined(klass)
          _refined = Module.new do
            include refine(klass) { yield if block_given? }
          end
          include _refined
        end
      end
    end
    
    class A
      def a
        "I am an 'a'"
      end
    end
    
    class B
      using Modulify
    
      include_refined(A) do
        def a
          super + " and not a 'b'"
        end
      end
    
      def b
        "I cannot say: " + a
      end
    end
    
    RSpec.describe B do
      it "can use refined methods from A" do
        expect(subject.b).to eq "I cannot say: I am an 'a' and not a 'b'"
      end
    end
    

    and suits as solution for the original problem.

提交回复
热议问题