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.
Railtie adds ‘to_prepare` callback, which will automatically load types.
Class Attribute Summary collapse
-
.types_list_class ⇒ Object
Class for ‘types_list`.
Class Method Summary collapse
Instance Method Summary collapse
-
#eager_load_types!(dir = nil) ⇒ Object
Shortcut to eager load all descendants.
-
#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.
21 22 23 |
# File 'lib/rails_stuff/types_tracker.rb', line 21 def types_list_class @types_list_class end |
Class Method Details
.extended(base) ⇒ Object
12 13 14 15 16 |
# File 'lib/rails_stuff/types_tracker.rb', line 12 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
#eager_load_types!(dir = nil) ⇒ Object
Shortcut to eager load all descendants.
47 48 49 |
# File 'lib/rails_stuff/types_tracker.rb', line 47 def eager_load_types!(dir = nil) RequireNested.require_nested(dir || 2) # skip 1 more because of deprecation end |
#inherited(base) ⇒ Object
Tracks all descendants automatically.
56 57 58 59 |
# File 'lib/rails_stuff/types_tracker.rb', line 56 def inherited(base) super base.register_type end |
#register_type(*args) ⇒ Object
Add ‘self` to `types_list`. Defines scope for ActiveRecord models.
27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/rails_stuff/types_tracker.rb', line 27 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.
62 63 64 |
# File 'lib/rails_stuff/types_tracker.rb', line 62 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.
42 43 44 |
# File 'lib/rails_stuff/types_tracker.rb', line 42 def unregister_type types_list.delete self end |