Class: ColdStorage::ArchiveRecord
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- ColdStorage::ArchiveRecord
- Defined in:
- lib/cold_storage/archive_record.rb
Overview
Abstract base of everything that lives in the archive database.
The connection is established lazily, on first use, so an application that has not configured the archive database yet still boots.
Class Method Summary collapse
- .connect! ⇒ self
- .database_config ⇒ Object
-
.reset_connection! ⇒ Object
Forget the established connection, e.g.
-
.source_model ⇒ Object
The model in the primary database an archived row came from.
-
.with_archive_connection(&block) ⇒ Object
Yields a checked out connection to the archive database.
Instance Method Summary collapse
-
#restore!(**options) ⇒ Integer
Moves this row (and, with
with:, its archived children) back into the primary database. - #source_model ⇒ Object
Class Method Details
.connect! ⇒ self
38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/cold_storage/archive_record.rb', line 38 def connect! return self if @connected MUTEX.synchronize do next if @connected database = ColdStorage.config.archive_database.to_sym assert_configured!(database) connects_to database: { writing: database, reading: database } @connected = true end self end |
.database_config ⇒ Object
67 68 69 70 71 72 73 74 |
# File 'lib/cold_storage/archive_record.rb', line 67 def database_config env = current_env ActiveRecord::Base.configurations.configs_for( env_name: env, name: ColdStorage.config.archive_database.to_s, include_hidden: true ) end |
.reset_connection! ⇒ Object
Forget the established connection, e.g. after changing the config in a test. The pool itself is left to ActiveRecord.
63 64 65 |
# File 'lib/cold_storage/archive_record.rb', line 63 def reset_connection! MUTEX.synchronize { @connected = false } end |
.source_model ⇒ Object
The model in the primary database an archived row came from.
15 16 17 |
# File 'lib/cold_storage/archive_record.rb', line 15 def self.source_model source_model_name&.constantize end |
.with_archive_connection(&block) ⇒ Object
Yields a checked out connection to the archive database.
(Named differently from ActiveRecord's own with_connection so that
nothing in ActiveRecord ends up calling this override.)
56 57 58 59 |
# File 'lib/cold_storage/archive_record.rb', line 56 def with_archive_connection(&block) connect! connection_pool.with_connection(&block) end |
Instance Method Details
#restore!(**options) ⇒ Integer
Moves this row (and, with with:, its archived children) back into the
primary database.
Invoice.archived.find(42).restore!(with: :all)
29 30 31 32 33 34 |
# File 'lib/cold_storage/archive_record.rb', line 29 def restore!(**) model = source_model raise NotArchivableError, "#{self.class} has no source model" if model.nil? ColdStorage.restore(model, [id], **) end |
#source_model ⇒ Object
19 20 21 |
# File 'lib/cold_storage/archive_record.rb', line 19 def source_model self.class.source_model end |