【问题标题】:Ruby Module Inclusion in Methods方法中包含 Ruby 模块
【发布时间】:2010-06-01 22:58:13
【问题描述】:

Foo 类中,我想在某些条件下包含方法 Bar

 module Bar
   def some_method
     "orly"
   end
 end

 class Foo
   def initialize(some_condition)
     if !some_condition
       "bar"
     else
       class << self; include Bar; end
     end
   end
 end

有没有更简洁(更清晰)的方法来实现方法中的include,而不必在单例类中完成?

【问题讨论】:

    标签: ruby metaprogramming mixins


    【解决方案1】:

    extend 相当于单例类中的include

    module Bar
      def some_method
        puts "orly"
      end
    end
    
    class Foo
      def initialize(some_condition)
        extend(Bar) if some_condition
      end
    end
    
    Foo.new(true).some_method # => "orly"
    Foo.new(false).some_method # raises NoMethodError
    

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 2017-12-19
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2016-02-24
      • 2013-10-28
      相关资源
      最近更新 更多