Class: DirtySeed::Association

Inherits:
Object
  • Object
show all
Extended by:
MethodMissingHelper
Defined in:
lib/dirty_seed/association.rb

Overview

Represents an Active Record association

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from MethodMissingHelper

define_addressee, define_method_missing, define_respond_to_missing?, forward_missing_methods_to

Constructor Details

#initialize(model, reflection) ⇒ DirtySeed::Association

Initializes an instance

Parameters:

  • model (DirtySeed::Model)
  • reflection (ActiveRecord::Reflection::BelongsToReflection)


15
16
17
18
# File 'lib/dirty_seed/association.rb', line 15

def initialize(model, reflection)
  @model = model
  @reflection = reflection
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



9
10
11
# File 'lib/dirty_seed/association.rb', line 9

def model
  @model
end

#reflectionObject (readonly)

Returns the value of attribute reflection.



9
10
11
# File 'lib/dirty_seed/association.rb', line 9

def reflection
  @reflection
end

Instance Method Details

#associated_modelsArray<Class>

Returns or defines associated_models

Returns:

  • (Array<Class>)

    a class inheriting from ApplicationRecord



52
53
54
# File 'lib/dirty_seed/association.rb', line 52

def associated_models
  polymorphic? ? polymorphic_associations : regular_associations
end

#attributeSymbol

Returns the attribute containing the foreign key

Returns:

  • (Symbol)


36
37
38
# File 'lib/dirty_seed/association.rb', line 36

def attribute
  :"#{name}_id"
end

#nameString

Returns the reflection name

Returns:

  • (String)


30
31
32
# File 'lib/dirty_seed/association.rb', line 30

def name
  reflection.name
end

#polymorphic?Boolean

Returns true if the reflection is polymorphic

Examples:

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns true

Returns:

  • (Boolean)


62
63
64
# File 'lib/dirty_seed/association.rb', line 62

def polymorphic?
  reflection.options[:polymorphic]
end

#type_keySymbol

Returns the attribute containing the foreign type (for polymorphic associations)

Examples:

Given Bar.belongs_to(:barable, polymorphic: true)
And self.model == Bar
Then it returns barable_type

Returns:

  • (Symbol)


46
47
48
# File 'lib/dirty_seed/association.rb', line 46

def type_key
  reflection.foreign_type&.to_sym
end

#valueObject

Returns a random instance matching the reflection

Returns:

  • (Object)

    an instance of a class inheriting from ApplicationRecord



22
23
24
25
26
# File 'lib/dirty_seed/association.rb', line 22

def value
  random_model = associated_models.sample
  random_id = random_model.pluck(:id).sample
  random_model.find_by(id: random_id)
end