-
-
Notifications
You must be signed in to change notification settings - Fork 253
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract
DatabaseTypeResolver
module from Rails/BulkChangeTable
cop
It could be reused in similar cases like #952.
- Loading branch information
Showing
3 changed files
with
69 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
# frozen_string_literal: true | ||
|
||
module RuboCop | ||
module Cop | ||
# A mixin to extend cops in order to determine the database type. | ||
# | ||
# This module automatically detect an adapter from `development` environment | ||
# in `config/database.yml` or the environment variable `DATABASE_URL` | ||
# when the `Database` option is not set. | ||
module DatabaseTypeResolver | ||
MYSQL = 'mysql' | ||
POSTGRESQL = 'postgresql' | ||
|
||
def database | ||
cop_config['Database'] || database_from_yaml || database_from_env | ||
end | ||
|
||
private | ||
|
||
def database_from_yaml | ||
return unless database_yaml | ||
|
||
case database_adapter | ||
when 'mysql2' | ||
MYSQL | ||
when 'postgresql' | ||
POSTGRESQL | ||
end | ||
end | ||
|
||
def database_from_env | ||
url = ENV['DATABASE_URL'].presence | ||
return unless url | ||
|
||
case url | ||
when %r{\Amysql2://} | ||
MYSQL | ||
when %r{\Apostgres(ql)?://} | ||
POSTGRESQL | ||
end | ||
end | ||
|
||
def database_yaml | ||
return unless File.exist?('config/database.yml') | ||
|
||
yaml = if YAML.respond_to?(:unsafe_load_file) | ||
YAML.unsafe_load_file('config/database.yml') | ||
else | ||
YAML.load_file('config/database.yml') | ||
end | ||
return unless yaml.is_a? Hash | ||
|
||
config = yaml['development'] | ||
return unless config.is_a?(Hash) | ||
|
||
config | ||
rescue Psych::SyntaxError | ||
# noop | ||
end | ||
|
||
def database_adapter | ||
database_yaml['adapter'] || database_yaml.first.last['adapter'] | ||
end | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters