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

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

Parameters:

  • name (Symbol)

    symbol representation of the class this belongs_to

  • prefix (Boolean) (defaults to: false)

    default: false; prefix the instance method attributes with the Enumble name, ex: House.color_black? instead of House.black?

  • scope_prefix (string) (defaults to: nil)

    optional, prefix the class scopes, for example: where_by will make it House.where_by_color(:black)

  • **options (Hash)

    additional options passed to belongs_to



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, **options)
  class_name = options.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, **options)

  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