简体   繁体   中英

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

I want to declare instance methods into Concern dynamically using constant from model.

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

But I get error:

NameError: uninitialized constant StatesHelper::STATES

But if I use constant into defined method, it works:

module StatesHelper
  extend ActiveSupport::Concern

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

How can I use constant from model in my case?

You can use self.included hook to get a reference to the including class at include time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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