Class: RuboCop::Cop::Rails::AddColumnIndex
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Rails::AddColumnIndex
- Extended by:
- AutoCorrector
- Includes:
- RangeHelp, MigrationsHelper
- Defined in:
- lib/rubocop/cop/rails/add_column_index.rb
Overview
Checks for migrations using ‘add_column` that have an `index` key. `add_column` does not accept `index`, but also does not raise an error for extra keys, so it is possible to mistakenly add the key without realizing it will not actually add an index.
Constant Summary collapse
- MSG =
'`add_column` does not accept an `index` key, use `add_index` instead.'- RESTRICT_ON_SEND =
%i[add_column].freeze
Instance Method Summary collapse
Methods included from MigrationsHelper
Instance Method Details
#add_column_with_index(node) ⇒ Object
28 29 30 31 32 33 |
# File 'lib/rubocop/cop/rails/add_column_index.rb', line 28 def_node_matcher :add_column_with_index, <<~PATTERN ( send nil? :add_column $_table $_column <(hash <$(pair {(sym :index) (str "index")} $_) ...>) ...> ) PATTERN |
#on_send(node) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/rubocop/cop/rails/add_column_index.rb', line 35 def on_send(node) table, column, pair, value = add_column_with_index(node) return unless pair add_offense(pair) do |corrector| corrector.remove(index_range(pair)) add_index = "add_index #{table.source}, #{column.source}" add_index_opts = '' if value.hash_type? hash = value.source_range.adjust(begin_pos: 1, end_pos: -1).source.strip add_index_opts = ", #{hash}" end corrector.insert_after(node, "\n#{add_index}#{add_index_opts}") end end |