代码之家  ›  专栏  ›  技术社区  ›  Federico Builes

方法中的Ruby模块包含

  •  0
  • Federico Builes  · 技术社区  · 16 年前

    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 在方法中,而不必在singleton类中这样做?

    1 回复  |  直到 16 年前
        1
  •  11
  •   Mark Rushakoff    16 年前

    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