Class: ActiveRecordSchemaScrapper::Associations

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of 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

Class Method Details

.typesObject



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

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

Instance Method Details

#eachObject



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
44
45
46
47
48
# File 'lib/active_record_schema_scrapper/associations.rb', line 17

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) || a.try(:source_reflection)).try(:name),
                   through:   a.try(:through) || a.try(:through_reflection).try(:name),
                   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

#errorsObject



10
11
12
13
# File 'lib/active_record_schema_scrapper/associations.rb', line 10

def errors
  to_a
  @errors
end

#to_aObject



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

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