代码之家  ›  专栏  ›  技术社区  ›  Sinan Taifour

Ruby需要全部还是全部?

  •  2
  • Sinan Taifour  · 技术社区  · 17 年前

    require

    class A module C

    class B
      include C
    end
    

    在我的特定情况下,我有一组大量相互依赖的文件,以及一个加载这些文件的加载器。举个例子,我将把文件集简化为4个文件(a.rb、b.rb、c.rb和w.rb)。以下是这些文件的列表:

    # In file a.rb
    class A
      @foo = []
      @foo.push("in A")
    
      def self.inherited(subclass)
        foo = @foo.dup
        subclass.instance_eval do
          @foo = foo
        end
      end
    
      def self.get_foo
        @foo
      end
    end
    
    # In file b.rb
    class B < A
      include C # if C is not already defined, the following line will not get executed although B will be defined.
      @foo.push("in B")
    end
    
    # In file c.rb
    module C
    end
    
    # In file w.rb
    class W < B
      @foo.push("in W")
    end
    

    # In file loader.rb
    files = Dir["*.rb"].reject { |f| f =~ /loader/ }
    files.sort! # just for the purpose of the example, to make them load in an order that causes the problem
    files.reject! { |f| require(f) rescue nil } while files.size > 0
    

    p W.get_foo ["in A", "in B", "in W"] ,这正是我想要的。

    self.inherited @foo ["in A", "in W"] .

    需要

    1 回复  |  直到 17 年前
        1
  •  5
  •   Ryan McGeary    17 年前

    如果一个文件依赖于另一个文件,则该文件本身应该需要依赖关系。例如, b.rb

    require 'a'
    require 'c'
    
    class B < A
      include C # if C is not already defined, the following line will not get executed although B will be defined.
      @foo.push("in B")
    end
    

    w.rb

    require 'b'
    
    class W < B
      @foo.push("in W")
    end
    

    b a c

    require

    推荐文章