Class: ActiveRecordSchemaScrapper::Associations

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/active_record_schema_scrapper/associations.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, types: self.class.types) ⇒ Associations



4
5
6
7
8
# File 'lib/active_record_schema_scrapper/associations.rb', line 4

def initialize(model:, types: self.class.types)
  @model  = model
  @types  = types
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



53
54
55
# File 'lib/active_record_schema_scrapper/associations.rb', line 53

def errors
  @errors
end

Class Method Details

.typesObject



49
50
51
# File 'lib/active_record_schema_scrapper/associations.rb', line 49

def self.types
  [:has_and_belongs_to_many, :belongs_to, :has_one, :has_many]
end

Instance Method Details

#eachObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active_record_schema_scrapper/associations.rb', line 12

def each
  return [] if abstract_class
  @each ||= types.each do |type|
    model.reflect_on_all_associations(type).each do |a|
      begin
        hash = if a.try(:delegate_reflection)
                 { source:    a.delegate_reflection.options[:source],
                   through:   a.delegate_reflection.options[:through],
                   dependent: a.delegate_reflection.options[:dependent],
                 }
               else
                 { source:    a.try(:delegate_reflection).try(:name),
                   through:   a.try(:through),
                   dependent: a.options[:dependent] }
               end.merge(name:        a.name,
                         foreign_key: a.foreign_key,
                         class_name:  a.klass.name,
                         type:        type)

        yield(ActiveRecordSchemaScrapper::Association.new(hash))
      rescue NameError => e
        errors << ErrorObject.new(
          class_name:     model.name,
          message:        "Missing model #{a.name.to_s.camelize.singularize} for association #{model.name}.belongs_to :#{a.name}",
          original_error: e,
          level:          :error,
          type:           :association
        )
      end
    end
  end
end

#to_aObject



45
46
47
# File 'lib/active_record_schema_scrapper/associations.rb', line 45

def to_a
  @to_a ||= map { |v| v }
end