Ruby include module's single method in model

前端 未结 4 2262
难免孤独
难免孤独 2021-02-19 00:28

I have a module of following

module SimpleTask
    def task1
    end
    def task2
    end
    def task3
    end
end

And I have a model which r

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 01:30

    I'm going to steal an example from delegate.rb, it restricts what it includes

    ...
    class Delegator < BasicObject
      kernel = ::Kernel.dup
      kernel.class_eval do
        [:to_s,:inspect,:=~,:!~,:===,:<=>,:eql?,:hash].each do |m|
          undef_method m
        end
      end
      include kernel
    ...
    

    becomes

    module PreciseInclude
    
      def include_except(mod, *except)
        the_module = mod.dup
        the_module.class_eval do
          except.each do |m|
            remove_method m # was undef_method, that prevents parent calls
          end
        end
        include the_module
      end
    end
    
    class Foo
      extend PreciseInclude
    
      include_except(SimpleTask, :task1, :task2)
    end
    
    Foo.instance_methods.grep(/task/) => [:task3]
    

    you can always flip it so instead of include it becomes include_only

    The catch is that remove_method won't work for nested modules, and using undef will prevent searching the entire hierarchy for that method.

提交回复
热议问题