【问题标题】:How include scopes write in module included by other module to a class? (rails 4.2)包含范围如何在其他模块包含的模块中写入类? (轨道 4.2)
【发布时间】:2017-01-21 05:41:45
【问题描述】:

我有一个类似的模块

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) module Bar include Foo 在被包含在类之前,所以我认为它不能给出参数。

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

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

【问题讨论】:

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


    【解决方案1】:

    我找到了这个方法,如果你有更好的...

    def self.included(klass)
      klass.instance_eval do
        include FooConcern
      end
    end
    

    在条形模块中

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多