Skip to content

Commit

Permalink
Merge pull request #655 from sunny/migration-class-name-ignores-gem-n…
Browse files Browse the repository at this point in the history
…ame-in-path

Ignore gem name in path for `MigrationClassName`
  • Loading branch information
koic committed Mar 15, 2022
2 parents 8813b04 + 7ec5f36 commit 60f0e8d
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
@@ -0,0 +1 @@
* [#656](https://github.com/rubocop/rubocop-rails/issues/656): Ignore gem name in paths for `Rails/MigrationClassName`. ([@sunny][])
13 changes: 10 additions & 3 deletions lib/rubocop/cop/rails/migration_class_name.rb
Expand Up @@ -26,9 +26,10 @@ class MigrationClassName < Base
def on_class(node)
snake_class_name = to_snakecase(node.identifier.source)

return if snake_class_name == basename_without_timestamp
basename = basename_without_timestamp_and_suffix
return if snake_class_name == basename

corrected_class_name = to_camelcase(basename_without_timestamp)
corrected_class_name = to_camelcase(basename)
message = format(MSG, corrected_class_name: corrected_class_name)

add_offense(node.identifier, message: message) do |corrector|
Expand All @@ -38,12 +39,18 @@ def on_class(node)

private

def basename_without_timestamp
def basename_without_timestamp_and_suffix
filepath = processed_source.file_path
basename = File.basename(filepath, '.rb')
basename = remove_gem_suffix(basename)
basename.sub(/\A\d+_/, '')
end

# e.g.: from `add_blobs.active_storage` to `add_blobs`.
def remove_gem_suffix(file_name)
file_name.sub(/\..+\z/, '')
end

def to_camelcase(word)
word.split('_').map(&:capitalize).join
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/migration_class_name_spec.rb
Expand Up @@ -26,4 +26,15 @@ class CreateUsers < ActiveRecord::Migration[7.0]
RUBY
end
end

context 'when the class name contains a dot in its file name' do
let(:filename) { 'db/migrate/20220101050505_add_blobs.active_storage.rb' }

it 'does not register an offense' do
expect_no_offenses(<<~RUBY, filename)
class AddBlobs < ActiveRecord::Migration[7.0]
end
RUBY
end
end
end

0 comments on commit 60f0e8d

Please sign in to comment.