Sha256: 9d4561e5fc12eb13b8ce7aceea61d17e1ff2553701fc6ff9ccbfec1c8acb70a6

Contents?: true

Size: 1.24 KB

Versions: 2

Compression:

Stored size: 1.24 KB

Contents

class PeakFlowUtils::DatabaseInitializerService < PeakFlowUtils::ApplicationService
  def execute
    path = File.realpath("#{File.dirname(__FILE__)}/../../migrations")
    create_schema_table unless schema_table_exists?

    Dir["#{path}/[0-9]*_*.rb"].sort.map do |filename|
      match = filename.match(/migrations\/(\d+)_(.+)\.rb\Z/)
      next unless match

      version = match[1]
      next if version_migrated?(version)

      require filename
      migration = match[2].camelize.constantize
      migration.migrate(:up)
      register_migration_migrated(version)
    end

    succeed!
  end

private

  def create_schema_table
    PeakFlowUtils::ApplicationRecord.connection.execute("CREATE TABLE schema_migrations (version VARCHAT)")
  end

  def register_migration_migrated(version)
    PeakFlowUtils::ApplicationRecord.connection.execute("INSERT INTO schema_migrations (version) VALUES ('#{version}')")
  end

  def schema_table_exists?
    PeakFlowUtils::ApplicationRecord.connection.execute("SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").any?
  end

  def version_migrated?(version)
    PeakFlowUtils::ApplicationRecord.connection.execute("SELECT * FROM schema_migrations WHERE version = '#{version}'").any?
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
peak_flow_utils-0.1.8 app/services/peak_flow_utils/database_initializer_service.rb
peak_flow_utils-0.1.7 app/services/peak_flow_utils/database_initializer_service.rb