如何将范围写入其他模块包含的模块中? (铁路4.2)

时间:2016-09-13 14:56:40

标签: ruby-on-rails module scope include ruby-on-rails-4.2

我有一个类似

的模块
module FooConcern
  extend ActiveSupport::Concern

  def self.included(klass)
    klass.instance_eval do
      scope :deleted, -> { where(state: STATE_DELETED) }
      scope :closed, -> { where(state: STATE_CLOSED) }
      scope :opened, -> { where(state: STATE_OPENED) }
    end
  end


  included do
    def deleted?
      state == STATE_DELETED
    end


    def closed?
      state == STATE_CLOSED
    end


    def opened?
      state == STATE_OPENED
    end
  end
end

和其他模块如:

module Bar
  include FooConcern
  include LotConcern
  include OfConcern
  include OtherConcern
  include ModuleConcern
end

和使用Bar的课程:

class Baz
  include Bar
end

错误:wrong number of arguments (given 0, expected 1)模块栏在包含在课堂之前包含Foo,所以我认为它不能给出参数。

如果我将范围直接放在阻止included do中,则引发错误:undefined method 'scope' for Bar:Module

如何按模块包含我的范围包括模块?

1 个答案:

答案 0 :(得分:0)

我发现这种方式,如果你有更好的......

def self.included(klass)
  klass.instance_eval do
    include FooConcern
  end
end
Bar模块中的