Module: StoryTeller::ImplicitMigration

Included in:
StoryTeller::InheritanceListener::ClassMethods
Defined in:
lib/story_teller/persistence.rb

Overview

The ImplicitMigration module

Constant Summary collapse

NoDatabasePattern =
%r{No database associated with Sequel::Model}.freeze
MigrationSetupTemplate =
'%<model>sSetup'.freeze
ModuleNamespaceDelimiterPattern =
/::/.freeze

Instance Method Summary collapse

Instance Method Details

#after_inherited(_subclass) ⇒ Object



245
246
247
# File 'lib/story_teller/persistence.rb', line 245

def after_inherited(_subclass)
  examine_schema
end

#before_inherited(subclass) ⇒ Object



238
239
240
241
242
243
# File 'lib/story_teller/persistence.rb', line 238

def before_inherited(subclass)
  return if self != Sequel::Model
  descendants << subclass
  log.debug "#{subclass} << #{self} [#{descendants}]"
  maybe_migrate(subclass)
end

#examine_schemaObject

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/MethodLength



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/story_teller/persistence.rb', line 251

def examine_schema
  descendants.each do |model_class|
    table_name = model_class.table_name
    indexes = self.db.indexes(table_name)
    columns = model_class.columns
    associations = model_class.associations

    log.debug "Table: #{table_name}"
    log.debug "Columns: #{columns.join(', ')}"
    log.debug "Indexes: #{indexes}"

    associations.each do |assoc_name, assoc_data|
      log.debug "Association: #{assoc_name} (#{assoc_data[:type]}) to #{assoc_data[:class_name]}"
    end

    log.debug "==========="
  end
end

#maybe_migrate(subclass) ⇒ Object

rubocop: enable Metrics/AbcSize rubocop: enable Metrics/MethodLength



272
273
274
275
276
277
278
279
280
281
# File 'lib/story_teller/persistence.rb', line 272

def maybe_migrate(subclass)
  migration_class = migration(subclass)
  log.debug "Found migration class: #{migration_class}"
  migration_class&.up
rescue Sequel::Error => e
  if NoDatabasePattern.match?(e.message)
    StoryTeller::Persistence.instance.connect
    retry
  end
end

#migration(model) ⇒ Object



283
284
285
286
287
288
289
290
291
# File 'lib/story_teller/persistence.rb', line 283

def migration(model)
  names = format(MigrationSetupTemplate, model: model).split(ModuleNamespaceDelimiterPattern)
  names.inject(Object) do |mod, class_name|
    mod.const_get(class_name)
  rescue StandardError => e
    log.warn "Error getting reference to migration model class: #{e.message}"
    next
  end
end