Class: Erbee::PolymorphicRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/erbee/polymorphic_registry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePolymorphicRegistry

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

#mapObject (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