【发布时间】:2017-05-06 01:11:24
【问题描述】:
我对文档中 ActiveSupport::Concern 上的 this 示例感到有些困惑:
module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
module ClassMethods
...
end
end
self.included 在您在类中包含或扩展模块时调用。 base 指的是对象,不管是类对象还是对象实例。 extend on base 将包含 Module 中的方法作为 base 上的单例方法。 include 会将方法添加到类对象的实例中。
然而,class_eval 也用于向类对象的实例添加实例方法。然而,scope 是一个类方法:
添加一个用于检索和查询对象的类方法。
既然scope是一个类方法,为什么这个例子使用class_eval而不是instance_eval?
【问题讨论】:
-
调用class_eval块时,就是调用类方法。这篇文章有帮助:engineering.appfolio.com/appfolio-engineering/2013/06/17/…
标签: ruby-on-rails ruby