Skip to content

Commit

Permalink
Fix loading database.yml file with aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Mar 10, 2023
1 parent 546cfbc commit df1fd92
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 21 deletions.
1 change: 1 addition & 0 deletions changelog/fix_loading_database_yml_with_aliases.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#947](https://github.com/rubocop/rubocop-rails/issues/947): Fix loading `database.yml` file with aliases. ([@fatkodima][])
17 changes: 12 additions & 5 deletions lib/rubocop/cop/rails/bulk_change_table.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'yaml'

module RuboCop
module Cop
module Rails
Expand Down Expand Up @@ -192,11 +194,8 @@ def database_from_yaml
def database_yaml
return nil 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
src = File.read('config/database.yml')
yaml = load_yaml(src)
return nil unless yaml.is_a? Hash

config = yaml['development']
Expand All @@ -207,6 +206,14 @@ def database_yaml
nil
end

def load_yaml(src)
if Psych::VERSION > '4.0'
YAML.safe_load(src, aliases: true)
else
YAML.load(src) # rubocop:disable Security/YAMLLoad
end
end

def support_bulk_alter?
case database
when MYSQL
Expand Down
31 changes: 15 additions & 16 deletions spec/rubocop/cop/rails/bulk_change_table_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -440,36 +440,35 @@ def change
end

context 'when `database.yml` is exists' do
let(:yaml) { nil }
let(:yaml) { '' }

before do
allow(File).to receive(:exist?).with('config/database.yml').and_return(true)
if YAML.respond_to?(:unsafe_load_file)
allow(YAML).to receive(:unsafe_load_file).with('config/database.yml').and_return(yaml)
else
allow(YAML).to receive(:load_file).with('config/database.yml').and_return(yaml)
end
allow(File).to receive(:read).and_call_original
allow(File).to receive(:read).with('config/database.yml').and_return(yaml)
end

context 'mysql2' do
let(:yaml) do
{
'development' => {
'adapter' => 'mysql2'
}
}
<<~YAML
default: &default
adapter: mysql2
development:
<<: *default
YAML
end

it_behaves_like 'offense for mysql'
end

context 'postgresql' do
let(:yaml) do
{
'development' => {
'adapter' => 'postgresql'
}
}
<<~YAML
default: &default
adapter: postgresql
development:
<<: *default
YAML
end

context 'with Rails 5.2', :rails52 do
Expand Down

0 comments on commit df1fd92

Please sign in to comment.