简体   繁体   English

Rails模块:如何在类方法中定义实例方法?

[英]Rails Modules: How to define instance methods inside a class method?

I'd like to create a module called StatusesExtension that defines a has_statuses method. 我想创建一个名为StatusesExtension的模块,它定义了一个has_statuses方法。 When a class extends StatusesExtension, it will have validations, scopes, and accessors for on those statuses. 当一个类扩展了StatusesExtension时,它将具有针对这些状态的验证,范围和访问器。 Here's the module: 这是模块:

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

Here's an example of a class that extends this module: 这是扩展此模块的类的示例:

def Question < ActiveRecord::Base
  extend StatusesExtension
  has_statuses :unanswered, :answered, :ignored
end

The problem I'm encountering is that while scopes are being defined, the instance methods (answered?, unanswered?, and ignored?) are not. 我遇到的问题是,在定义范围时,实例方法(回答?,未回答?,并忽略?)不是。 For example: 例如:

> Question.answered
=> [#<Question id: 1, ...>]
> Question.answered.first.answered?
=> false # Should be true

How can I use modules to define both class methods (scopes, validations) and instance methods (accessors) within the context of a single class method (has_statuses) of a module? 如何在模块的单个类方法(has_statuses)的上下文中使用模块来定义类方法(范围,验证)和实例方法(访问器)?

Thank you! 谢谢!

As the comments have said, the method is being defined, just not working as expected. 正如评论所说,该方法正在定义,只是没有按预期工作。 I suspect this is because you are comparing a string with a symbol within the method ( status_names is an array of symbols, and status will be a string). 我怀疑这是因为您正在将字符串与方法中的符号进行比较( status_names是一个符号数组, status将是一个字符串)。 Try the following: 请尝试以下方法:

status_names.each do |status_name|
  define_method "#{status_name}?" do
    status == status_name.to_s
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM