Class: Trains::Visitor::Model

Inherits:
Base
  • Object
show all
Defined in:
lib/trains/visitor/model.rb

Overview

Visit ActiveRecord models and add migrations for reference fields

Constant Summary collapse

POSSIBLE_ASSOCIATIONS =
%i[
  has_many
  belongs_to
  has_one
  has_and_belongs_to_many
  ignored_columns=
].freeze
MODEL_PARENT_CLASSES =
%w[
  ApplicationRecord
  ActiveRecord::Base
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeModel

skipcq: RB-LI1087



21
22
23
# File 'lib/trains/visitor/model.rb', line 21

def initialize
  @result = []
end

Instance Attribute Details

#resultObject (readonly)

Returns the value of attribute result.



18
19
20
# File 'lib/trains/visitor/model.rb', line 18

def result
  @result
end

Instance Method Details

#on_class(node) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/trains/visitor/model.rb', line 25

def on_class(node)
  return unless node.parent_class
  return unless MODEL_PARENT_CLASSES.include? node.parent_class.source

  @model_class = node.identifier.source
  node.each_descendant(:send) { |send_node| parse_model(send_node) }
end

#parse_model(node) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/trains/visitor/model.rb', line 33

def parse_model(node)
  return unless POSSIBLE_ASSOCIATIONS.include?(node.method_name)

  if node.method_name == :ignored_columns=
    return if node.arguments.nil?
    return unless node.arguments.first.is_a? RuboCop::AST::ArrayNode

    arguments = node.arguments.first.to_a
    arguments = arguments.select do |child|
      child.is_a?(RuboCop::AST::SymbolNode) || child.is_a?(RuboCop::AST::StrNode)
    end.map(&:value)

    @result << DTO::Migration.new(
      @model_class,
      :ignore_column,
      [*arguments.map { |arg| DTO::Field.new(arg.to_sym, nil) }],
      nil
    )

    return
  end

  @result << DTO::Migration.new(
    @model_class,
    :add_column,
    [DTO::Field.new(node.arguments.first.value.to_sym, :bigint)],
    nil
  )

  return unless node.method_name == :has_and_belongs_to_many

  @result <<
    DTO::Migration.new(
      node.arguments.first.value.to_s.singularize.camelize,
      :add_column,
      [DTO::Field.new(@model_class.tableize.to_sym, :bigint)],
      nil
    )
end