在Ruby中使用多级模块结构调用类方法

时间:2013-07-29 13:54:08

标签: ruby-on-rails ruby

我的控制器类中包含一些模块。这些模块定义before_filter

module BasicFeatures
  def filter_method
    ...
  end
  def self.included(base)
    base.before_filter(:filter_method)
    ...
  end
end

module AdvancedFeatures
  include BasicFeatures
  ...
end

班级:

class BasicController < ApplicationController
    include BasicFeatures
end

class AdvancedController < ApplicationController
    include AdvancedFeatures
end
  1. BasicFeatures模块中包含AdvancedFeatures模块时,其中没有before_filter个方法。
  2. AdvancedController没有收到before_filter来电。
  3. 我需要两个控制器来获取before_filter而没有任何代码重复。我不知道我是否使用最佳方法,所以我愿意接受任何建议。

2 个答案:

答案 0 :(得分:5)

这就是创建ActiveSupport::Concern的原因。

module BasicFeatures
  extend ActiveSupport::Concern

  included do
    before_filter :require_user
  end

  def this_is_an_instance_method
    'foo'
  end

  module ClassMethods
    def this_is_a_class_method
      'bar'
    end
  end
end

class SomeClass
  include BasicFeatures
end

SomeClass.new.this_is_an_instance_method #=> 'foo'

您还可以嵌套它们 - 也就是说,创建包含关注点的问题 - 并且一切都将按预期工作。并here are the docs

答案 1 :(得分:0)

你可以试试这个。您可以在类包括AdvancedFeatures

的类中包含BasicFeatures模块,而不是在AdvancedFeatures中包含该模块
module BasicFeatures
    def filter_method
      #code....
    end

    #some others basic methods...

    def self.included(base)
      base.before_filter(:filter_method)
      #some other class method calls
    end
end

module AdvancedFeatures
  def self.included klass
    klass.class_eval do
      include BasicFeatures
    end
  end

  #some advanced methods
end