From 7c2a6e0d13be806623dde27a9d7d91a30f11eae5 Mon Sep 17 00:00:00 2001 From: Joe Lind Date: Tue, 13 Feb 2024 16:35:50 -0500 Subject: [PATCH] Create table in same database as `superclass` --- lib/with_model/model.rb | 2 +- lib/with_model/table.rb | 10 +++++----- spec/with_model_spec.rb | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/with_model/model.rb b/lib/with_model/model.rb index 34c3e58..6606853 100644 --- a/lib/with_model/model.rb +++ b/lib/with_model/model.rb @@ -76,7 +76,7 @@ def stubber end def table - @table ||= Table.new table_name, @table_options, &@table_block + @table ||= Table.new table_name, @table_options, connection: @superclass.connection, &@table_block end def table_name diff --git a/lib/with_model/table.rb b/lib/with_model/table.rb index ba37198..d70872d 100644 --- a/lib/with_model/table.rb +++ b/lib/with_model/table.rb @@ -8,12 +8,14 @@ module WithModel class Table # @param [Symbol] name The name of the table to create. # @param options Passed to ActiveRecord `create_table`. + # @param connection The connection to use for creating the table. # @param block Passed to ActiveRecord `create_table`. # @see https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table - def initialize(name, options = {}, &block) + def initialize(name, options = {}, connection: ActiveRecord::Base.connection, &block) @name = name.freeze @options = options.freeze @block = block + @connection = connection end # Creates the table with the initialized options. Drops the table if @@ -29,6 +31,8 @@ def destroy private + attr_reader :connection + def exists? if connection.respond_to?(:data_source_exists?) connection.data_source_exists?(@name) @@ -36,9 +40,5 @@ def exists? connection.table_exists?(@name) end end - - def connection - ActiveRecord::Base.connection - end end end diff --git a/spec/with_model_spec.rb b/spec/with_model_spec.rb index 6f84ef3..6ae9df6 100644 --- a/spec/with_model_spec.rb +++ b/spec/with_model_spec.rb @@ -391,4 +391,25 @@ class BlogPostParent < ActiveRecord::Base expect(BlogPost.with_model?).to be true end end + + context "with 'superclass' that connects to a different database" do + class ApplicationRecordInDifferentDatabase < ActiveRecord::Base + self.abstract_class = true + establish_connection(ActiveRecord::Base.connection_pool.db_config.configuration_hash) + end + + after(:all) do + Object.__send__(:remove_const, 'ApplicationRecordInDifferentDatabase') + end + + with_model :BlogPost, superclass: ApplicationRecordInDifferentDatabase do + table do |t| + t.string 'title' + end + end + + it 'uses the superclass connection' do + expect(BlogPost.connection.tables).to include(BlogPost.table_name) + end + end end