Module: Enumbler::ClassMethods
- Defined in:
- lib/enumbler.rb
Overview
Include these ClassMethods in your base ApplicationRecord model to bestow
any of your models with the ability to be connected to an Enumbled relation
in the same way you would use belongs_to now you use enumbled_to.
class ApplicationRecord > ActiveRecord::Base
include Enumbler
self.abstract_class = true
end
class House < ApplicationRecord
enumbled_to :color
end
Instance Method Summary collapse
-
#enumbled_to(name, scope = nil, prefix: false, scope_prefix: nil, **options) ⇒ Object
Defines the relationship between a model and the Enumbled class.
Instance Method Details
#enumbled_to(name, scope = nil, prefix: false, scope_prefix: nil, **options) ⇒ Object
Defines the relationship between a model and the Enumbled class. Use this
in lieu of belongs_to to establish that relationship. It requires a
model that has defined one or more Enumbles.
# in your migration
create_table :houses, force: true do |t|
t.references :color, foreign_key: true, null: false
end
class ApplicationRecord > ActiveRecord::Base
include Enumbler
self.abstract_class = true
end
class House < ApplicationRecord
enumbled_to :color
end
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/enumbler.rb', line 79 def enumbled_to(name, scope = nil, prefix: false, scope_prefix: nil, **) class_name = .fetch(:class_name, name.to_s.classify) enumbled_model = class_name.constantize unless enumbled_model.respond_to?(:enumbles) raise Error, "The model #{class_name} does not have any enumbles defined. " \ "You can add them via `#{class_name}.enumble :blue, 1`." end belongs_to(name, scope, **) define_helper_attributes(name) define_dynamic_methods_for_enumbled_to_models(name, enumbled_model, prefix: prefix, scope_prefix: scope_prefix) rescue NameError raise Error, "The model #{class_name} cannot be found. Uninitialized constant." end |