Class: Erbee::PolymorphicRegistry
- Inherits:
-
Object
- Object
- Erbee::PolymorphicRegistry
- Defined in:
- lib/erbee/polymorphic_registry.rb
Instance Attribute Summary collapse
-
#map ⇒ Object
readonly
The data structure is: { polymorphic_name => { association_name => [Array of owner class names] } } For example: { “imageable” => { “images” => [“User”, “Article”] } } This holds the models that declare something like ‘has_many :images, as: :imageable’.
Instance Method Summary collapse
-
#add(polymorphic_name, association_name, owner_class) ⇒ Object
Register a has_many …
-
#initialize ⇒ PolymorphicRegistry
constructor
A new instance of PolymorphicRegistry.
-
#possible_owners(polymorphic_name) ⇒ Object
For example, if polymorphic_name = “imageable”, possible_owners(“imageable”) might return [“User”, “Article”, …] because each one has ‘has_many :images, as: :imageable’.
Constructor Details
#initialize ⇒ PolymorphicRegistry
Returns a new instance of PolymorphicRegistry.
9 10 11 12 |
# File 'lib/erbee/polymorphic_registry.rb', line 9 def initialize # Initialize @map so that each key references a nested hash @map = Hash.new { |h, k| h[k] = {} } end |
Instance Attribute Details
#map ⇒ Object (readonly)
The data structure is: { polymorphic_name => { association_name => [Array of owner class names] } } For example: { “imageable” => { “images” => [“User”, “Article”] } } This holds the models that declare something like ‘has_many :images, as: :imageable’.
7 8 9 |
# File 'lib/erbee/polymorphic_registry.rb', line 7 def map @map end |
Instance Method Details
#add(polymorphic_name, association_name, owner_class) ⇒ Object
Register a has_many … as: :polymorphic_name For example, add(“imageable”, “images”, “User”) means:
"User" has 'has_many :images, as: :imageable'
17 18 19 20 |
# File 'lib/erbee/polymorphic_registry.rb', line 17 def add(polymorphic_name, association_name, owner_class) @map[polymorphic_name][association_name] ||= [] @map[polymorphic_name][association_name] << owner_class end |
#possible_owners(polymorphic_name) ⇒ Object
For example, if polymorphic_name = “imageable”, possible_owners(“imageable”) might return [“User”, “Article”, …] because each one has ‘has_many :images, as: :imageable’.
25 26 27 28 29 |
# File 'lib/erbee/polymorphic_registry.rb', line 25 def possible_owners(polymorphic_name) # We gather all associated class arrays across the nested hash and flatten them: # @map["imageable"].values.flatten.uniq @map[polymorphic_name].values.flatten.uniq end |