我想创建一个名为 StatusesExtension 的模块,它定义了一个 has_statuses 方法。当一个类扩展 StatusesExtension 时,它将具有这些状态的验证、范围和访问器。这是模块:
module StatusesExtension
def has_statuses(*status_names)
validates :status, presence: true, inclusion: { in: status_names }
# Scopes
status_names.each do |status_name|
scope "#{status_name}", where(status: status_name)
end
# Accessors
status_names.each do |status_name|
define_method "#{status_name}?" do
status == status_name
end
end
end
end
这是扩展此模块的类的示例:
def Question < ActiveRecord::Base
extend StatusesExtension
has_statuses :unanswered, :answered, :ignored
end
我遇到的问题是,在定义范围时,实例方法(已回答?、未回答?和忽略?)没有。例如:
> Question.answered
=> [#<Question id: 1, ...>]
> Question.answered.first.answered?
=> false # Should be true
如何使用模块在模块的单个类方法 (has_statuses) 的上下文中定义类方法(范围、验证)和实例方法(访问器)?
谢谢!