Skip to content

Commit

Permalink
keep cache when switching databases
Browse files Browse the repository at this point in the history
  • Loading branch information
langalex committed Mar 28, 2024
1 parent aea3fbb commit 6cd3512
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
24 changes: 17 additions & 7 deletions lib/couch_potato/database.rb
Original file line number Diff line number Diff line change
Expand Up @@ -197,28 +197,38 @@ def inspect #:nodoc:
# returns the underlying CouchRest::Database instance
attr_reader :couchrest_database

attr_accessor :switched_databases

# returns a new database instance connected to the CouchDB database
# with the given name. the name is passed through the
# additional_databases configuration to resolve it to a database
# configured there.
# if the current database has a cache, the new database will receive
# a cleared copy of it.
def switch_to(database_name)
resolved_database_name = CouchPotato.resolve_database_name(database_name)
self
self.switched_databases ||= {}
if (db = switched_databases[database_name || :default])
return db
end
switched_databases[name || :default] ||= self


resolved_database_name = CouchPotato.resolve_database_name(database_name) unless database_name == :default
couchrest_database = resolved_database_name ? CouchPotato.couchrest_database_for_name(resolved_database_name) : CouchPotato.couchrest_database
new_db = self
.class
.new(CouchPotato.couchrest_database_for_name(resolved_database_name), name: database_name)
.new(couchrest_database, name: database_name == :default ? nil : database_name)
.tap(&copy_clear_cache_proc)

new_db.switched_databases = switched_databases
new_db
end

# returns a new database instance connected to the default CouchDB database.
# if the current database has a cache, the new database will receive
# a cleared copy of it.
def switch_to_default
self
.class
.new(CouchPotato.couchrest_database)
.tap(&copy_clear_cache_proc)
switch_to(:default)
end

private
Expand Down
8 changes: 8 additions & 0 deletions spec/unit/database_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,14 @@ def set_errors

expect(new_db.cache).to be_nil
end

it 're-uses the original cache when switching back to the original database' do
db.cache = { key: 'value' }
new_db = db.switch_to('db2')
original_db = new_db.switch_to_default

expect(original_db.cache).to have_key(:key)
end
end

describe CouchPotato::Database, '#switch_to_default' do
Expand Down

0 comments on commit 6cd3512

Please sign in to comment.