2020-10-24 23:57:45 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
require 'find'
|
|
|
|
|
|
|
|
class RequireMigration
|
2021-01-29 00:20:46 +05:30
|
|
|
class AutoLoadError < RuntimeError
|
|
|
|
MESSAGE = "Can not find any migration file for `%{file_name}`!\n" \
|
|
|
|
"You can try to provide the migration file name manually."
|
|
|
|
|
|
|
|
def initialize(file_name)
|
|
|
|
message = format(MESSAGE, file_name: file_name)
|
|
|
|
|
|
|
|
super(message)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
MIGRATION_FOLDERS = %w[db/migrate db/post_migrate].freeze
|
2020-10-24 23:57:45 +05:30
|
|
|
SPEC_FILE_PATTERN = /.+\/(?<file_name>.+)_spec\.rb/.freeze
|
|
|
|
|
|
|
|
class << self
|
|
|
|
def require_migration!(file_name)
|
|
|
|
file_paths = search_migration_file(file_name)
|
2021-06-08 01:23:25 +05:30
|
|
|
raise AutoLoadError, file_name unless file_paths.first
|
2020-10-24 23:57:45 +05:30
|
|
|
|
|
|
|
require file_paths.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def search_migration_file(file_name)
|
2021-01-29 00:20:46 +05:30
|
|
|
migration_folders.flat_map do |path|
|
2020-10-24 23:57:45 +05:30
|
|
|
migration_path = Rails.root.join(path).to_s
|
|
|
|
|
|
|
|
Find.find(migration_path).grep(/\d+_#{file_name}\.rb/)
|
|
|
|
end
|
|
|
|
end
|
2021-01-29 00:20:46 +05:30
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def migration_folders
|
|
|
|
MIGRATION_FOLDERS
|
|
|
|
end
|
2020-10-24 23:57:45 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-06-08 01:23:25 +05:30
|
|
|
RequireMigration.prepend_mod_with('RequireMigration')
|
2021-01-29 00:20:46 +05:30
|
|
|
|
2020-10-24 23:57:45 +05:30
|
|
|
def require_migration!(file_name = nil)
|
|
|
|
location_info = caller_locations.first.path.match(RequireMigration::SPEC_FILE_PATTERN)
|
|
|
|
file_name ||= location_info[:file_name]
|
|
|
|
|
|
|
|
RequireMigration.require_migration!(file_name)
|
|
|
|
end
|