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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With