如何在Ruby中的metaclass和普通类中包含几个模块

时间:2013-03-26 10:01:28

标签: ruby module

我有几个模块,比如Capybara::DSLRSpec::MatchersRouterCommon

我希望能够在我的代码中的任何地方使用这些模块中的方法。目前我试图这样做:

module Helper
  # from http://stackoverflow.com/a/4663029/841064
  module ClassMethods
    include Capybara::DSL
    include RSpec::Matchers
    include Router
    include Common
  end

  include Capybara::DSL
  include RSpec::Matchers
  include Router
  include Common

  extend ClassMethods

  def self.included(other)
    other.extend(ClassMethods)
  end
end

然后我想用它作为:

module A
  include Helper

  class << self
    # all methods from 4 modules are available in all methods here
  end

  # all methods from 4 modules are available in all methods here
end


class B
  include Helper

  class << self
    # all methods from 4 modules are available in all methods here
  end

  # all methods from 4 modules are available in all methods here. But they aren't available here
end

您是否知道一种方法可以将所有这些方法作为实例和类方法访问,当它们包含在模块或类中时?

1 个答案:

答案 0 :(得分:-1)

如果要在要包含模块的类中同时使用includeextend,该怎么办?

module Helper
  include Capybara::DSL
  include RSpec::Matchers
  include Router
  include Common
end

module A
  # Gives methods on instance
  include Helper

  # Gives methods on class
  extend Helper

  #...
end