Rails:使用模型中的常量将实例方法定义到关注中

Rails: Use constants from model for define instance methods into Concern

我想使用模型中的常量动态地将实例方法声明到 Concern 中。

class Item < ApplicationRecord
  STATES = %w(active disabled).freeze
  include StatesHelper
end

module StatesHelper
  extend ActiveSupport::Concern

  # instance methods
  self.class::STATES.each do |state|
    define_method "#{state}?" do
      self.state == state
    end
  end
end

但是我得到错误:

NameError: uninitialized constant StatesHelper::STATES

但是如果我在定义的方法中使用常量,它会起作用:

module StatesHelper
  extend ActiveSupport::Concern

  # instance methods
  def some_method
    puts self.class::STATES # => ["active", "disabled"]
  end
end

如何在我的案例中使用模型中的常量?

您可以使用 self.included 挂钩在包含时获取对包含 class 的引用。

module StatesHelper
  extend ActiveSupport::Concern

  def self.included(base)
    base::STATES.each do |state|
      define_method "#{state}?" do
        self.state == state
      end
    end
  end
end

class Item
  STATES = %w(active disabled).freeze
  include StatesHelper
end

item = Item.new
item.respond_to?(:active?) # => true
item.respond_to?(:disabled?) # => true