From 0401f50d645b8cb30c1221099141393a5d570422 Mon Sep 17 00:00:00 2001 From: Hartley McGuire Date: Sat, 18 Feb 2023 17:28:22 -0500 Subject: [PATCH] Allow 3-tier shared config in database.yml Previously, the shared config hash would be merged with all database configurations defined in database.yml. This commit makes the shared hash 3-tier aware so that it can be used to share configuration across environments but only with matching configuration names. For example: ```yaml shared: one: migrations_path: "db/one" two: migrations_path: "db/two" development: one: adapter: sqlite3 two: adapter: sqlite3 production: one: adapter: mysql2 two: adapter: mysql2 ``` Will now properly set the migration_path for the one and two configurations in both development and production. --- .../lib/rails/application/configuration.rb | 10 +++++++-- .../test/application/configuration_test.rb | 22 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index b7d458ae8753f..d8603ff78709c 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -417,8 +417,14 @@ def database_configuration if (shared = loaded_yaml.delete("shared")) loaded_yaml.each do |env, config| if config.is_a?(Hash) && config.values.all?(Hash) - config.map do |name, sub_config| - sub_config.reverse_merge!(shared) + if shared.is_a?(Hash) && shared.values.all?(Hash) + config.map do |name, sub_config| + sub_config.reverse_merge!(shared[name]) + end + else + config.map do |name, sub_config| + sub_config.reverse_merge!(shared) + end end else config.reverse_merge!(shared) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index d988b9c0233cb..d8cf199f58b49 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -2180,6 +2180,28 @@ def index assert_equal "dev_db", ar_config["development"]["primary"]["database"] end + test "loads database.yml using 3-tier shared keys with a 3-tier config" do + app_file "config/database.yml", <<-YAML + shared: + one: + migrations_path: "db/one" + two: + migrations_path: "db/two" + + development: + one: + adapter: sqlite3 + two: + adapter: sqlite3 + YAML + + app "development" + + ar_config = Rails.configuration.database_configuration + assert_equal "db/one", ar_config["development"]["one"]["migrations_path"] + assert_equal "db/two", ar_config["development"]["two"]["migrations_path"] + end + test "config.action_mailer.show_previews defaults to true in development" do app "development"