Rails:使用模型中的常量将实例方法定义为Concern

时间:2018-07-19 15:19:32

标签: ruby-on-rails activesupport-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:未初始化的常量StatesHelper :: STATES

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

module StatesHelper
  extend ActiveSupport::Concern

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

在我的情况下,如何使用模型中的常量?

1 个答案:

答案 0 :(得分:0)

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

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