module RailsStuff::TypesTracker

Adds `types_list` method which tracks all descendants. Also allows to remove any of descendants from this list. Useful for STI models to track all available types.

Use with RequireNested to preload all nested classes.

Attributes

types_list_class[RW]

Class for `types_list`. Default to `Array`. You can override it for all models, or assign new value to specific model via `lypes_list=` right after extending.

Public Class Methods

extended(base) click to toggle source
# File lib/rails_stuff/types_tracker.rb, line 11
def extended(base)
  base.class_attribute :types_list, instance_accessor: false
  base.types_list = types_list_class.new
  base.instance_variable_set(:@_types_tracker_base, base)
end

Public Instance Methods

inherited(base) click to toggle source

Tracks all descendants automatically.

Calls superclass method
# File lib/rails_stuff/types_tracker.rb, line 46
def inherited(base)
  super
  base.register_type
end
register_type(*args) click to toggle source

Add `self` to `types_list`. Defines scope for ActiveRecord models.

# File lib/rails_stuff/types_tracker.rb, line 26
def register_type(*args)
  if types_list.respond_to?(:add)
    types_list.add self, *args
  else
    types_list << self
  end
  if types_tracker_base.respond_to?(:scope) &&
      !types_tracker_base.respond_to?(model_name.element)
    type_name = name
    types_tracker_base.scope model_name.element, -> { where(type: type_name) }
  end
end
types_tracker_base() click to toggle source

Class that was initilly extended with TypesTracker.

# File lib/rails_stuff/types_tracker.rb, line 52
def types_tracker_base
  @_types_tracker_base || superclass.types_tracker_base
end
unregister_type() click to toggle source

Remove `self` from `types_list`. It doesnt remove generated scope from ActiveRecord models, 'cause it potentialy can remove other methods.

# File lib/rails_stuff/types_tracker.rb, line 41
def unregister_type
  types_list.delete self
end