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

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.types_list_classObject

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.



19
20
21
# File 'lib/rails_stuff/types_tracker.rb', line 19

def types_list_class
  @types_list_class
end

Class Method Details

.extended(base) ⇒ Object



11
12
13
14
# 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
end

Instance Method Details

#eager_load_types!(dir = nil) ⇒ Object

Shortcut to eager load all descendants.



39
40
41
42
# File 'lib/rails_stuff/types_tracker.rb', line 39

def eager_load_types!(dir = nil)
  dir ||= "#{Rails.root}/app/models/#{to_s.underscore}"
  Dir["#{dir}/*.rb"].each { |file| require_dependency file }
end

#inherited(base) ⇒ Object

Tracks all descendants automatically.



45
46
47
48
# File 'lib/rails_stuff/types_tracker.rb', line 45

def inherited(base)
  super
  base.register_type
end

#register_type(*args) ⇒ Object

Add ‘self` to `types_list`.



25
26
27
28
29
30
31
# File 'lib/rails_stuff/types_tracker.rb', line 25

def register_type(*args)
  if types_list.respond_to?(:add)
    types_list.add self, *args
  else
    types_list << self
  end
end

#unregister_typeObject

Remove ‘self` from `types_list`.



34
35
36
# File 'lib/rails_stuff/types_tracker.rb', line 34

def unregister_type
  types_list.delete self
end