Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 624
vk26 Avatar asked Mar 09 '26 06:03

vk26


1 Answers

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
like image 84
Sergio Tulentsev Avatar answered Mar 10 '26 21:03

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!