Commit 54b63919 authored by Toon Claes's avatar Toon Claes

Make add_reference cop accept a hash for :index

It might happen you want to make the reference column have a unique
value, or you want to create partial indexes. So instead of only
accepting a `true` value, also accept a hash of options.
parent b18556f0
...@@ -8,7 +8,7 @@ module RuboCop ...@@ -8,7 +8,7 @@ module RuboCop
class AddReference < RuboCop::Cop::Cop class AddReference < RuboCop::Cop::Cop
include MigrationHelpers include MigrationHelpers
MSG = '`add_reference` requires `index: true`' MSG = '`add_reference` requires `index: true` or `index: { options... }`'
def on_send(node) def on_send(node)
return unless in_migration?(node) return unless in_migration?(node)
...@@ -33,7 +33,12 @@ module RuboCop ...@@ -33,7 +33,12 @@ module RuboCop
private private
def index_enabled?(pair) def index_enabled?(pair)
hash_key_type(pair) == :sym && hash_key_name(pair) == :index && pair.children[1].true_type? return unless hash_key_type(pair) == :sym
return unless hash_key_name(pair) == :index
index = pair.children[1]
index.true_type? || index.hash_type?
end end
def hash_key_type(pair) def hash_key_type(pair)
......
...@@ -29,7 +29,7 @@ describe RuboCop::Cop::Migration::AddReference do ...@@ -29,7 +29,7 @@ describe RuboCop::Cop::Migration::AddReference do
expect_offense(<<~RUBY) expect_offense(<<~RUBY)
call do call do
add_reference(:projects, :users) add_reference(:projects, :users)
^^^^^^^^^^^^^ `add_reference` requires `index: true` ^^^^^^^^^^^^^ `add_reference` requires `index: true` or `index: { options... }`
end end
RUBY RUBY
end end
...@@ -38,7 +38,7 @@ describe RuboCop::Cop::Migration::AddReference do ...@@ -38,7 +38,7 @@ describe RuboCop::Cop::Migration::AddReference do
expect_offense(<<~RUBY) expect_offense(<<~RUBY)
def up def up
add_reference(:projects, :users, index: false) add_reference(:projects, :users, index: false)
^^^^^^^^^^^^^ `add_reference` requires `index: true` ^^^^^^^^^^^^^ `add_reference` requires `index: true` or `index: { options... }`
end end
RUBY RUBY
end end
...@@ -50,5 +50,13 @@ describe RuboCop::Cop::Migration::AddReference do ...@@ -50,5 +50,13 @@ describe RuboCop::Cop::Migration::AddReference do
end end
RUBY RUBY
end end
it 'does not register an offense when the index is unique' do
expect_no_offenses(<<~RUBY)
def up
add_reference(:projects, :users, index: { unique: true } )
end
RUBY
end
end end
end end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment