Module: RailsStuff::TypesTracker
- Defined in:
- lib/rails_stuff/types_tracker.rb
Overview
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.
Class Attribute Summary collapse
-
.types_list_class ⇒ Object
Class for ‘types_list`.
Class Method Summary collapse
Instance Method Summary collapse
-
#inherited(base) ⇒ Object
Tracks all descendants automatically.
-
#register_type(*args) ⇒ Object
Add ‘self` to `types_list`.
-
#types_tracker_base ⇒ Object
Class that was initilly extended with TypesTracker.
-
#unregister_type ⇒ Object
Remove ‘self` from `types_list`.
Class Attribute Details
.types_list_class ⇒ Object
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.
20 21 22 |
# File 'lib/rails_stuff/types_tracker.rb', line 20 def types_list_class @types_list_class end |
Class Method Details
.extended(base) ⇒ Object
11 12 13 14 15 |
# 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 |
Instance Method Details
#inherited(base) ⇒ Object
Tracks all descendants automatically.
46 47 48 49 |
# File 'lib/rails_stuff/types_tracker.rb', line 46 def inherited(base) super base.register_type end |
#register_type(*args) ⇒ Object
Add ‘self` to `types_list`. Defines scope for ActiveRecord models.
26 27 28 29 30 31 32 33 34 35 36 37 |
# 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 ⇒ Object
Class that was initilly extended with TypesTracker.
52 53 54 |
# File 'lib/rails_stuff/types_tracker.rb', line 52 def types_tracker_base @_types_tracker_base || superclass.types_tracker_base end |
#unregister_type ⇒ Object
Remove ‘self` from `types_list`. It doesnt remove generated scope from ActiveRecord models, ’cause it potentialy can remove other methods.
41 42 43 |
# File 'lib/rails_stuff/types_tracker.rb', line 41 def unregister_type types_list.delete self end |