2020-08-19 17:10:32 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
require 'find'
|
|
|
|
|
|
|
|
class RequireMigration
|
2020-10-27 11:08:39 -04:00
|
|
|
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
|
|
|
|
|
2020-11-12 22:09:15 -05:00
|
|
|
MIGRATION_FOLDERS = %w[db/migrate db/post_migrate].freeze
|
2021-10-18 20:10:29 -04:00
|
|
|
SPEC_FILE_PATTERN = %r{.+/(?:\d+_)?(?<file_name>.+)_spec\.rb}.freeze
|
2020-08-19 17:10:32 -04:00
|
|
|
|
|
|
|
class << self
|
|
|
|
def require_migration!(file_name)
|
|
|
|
file_paths = search_migration_file(file_name)
|
2021-05-04 11:10:36 -04:00
|
|
|
raise AutoLoadError, file_name unless file_paths.first
|
2020-08-19 17:10:32 -04:00
|
|
|
|
|
|
|
require file_paths.first
|
|
|
|
end
|
|
|
|
|
|
|
|
def search_migration_file(file_name)
|
2021-10-18 20:10:29 -04:00
|
|
|
migration_file_pattern = /\A\d+_#{file_name}\.rb\z/
|
|
|
|
|
2020-10-27 11:08:39 -04:00
|
|
|
migration_folders.flat_map do |path|
|
2020-08-19 17:10:32 -04:00
|
|
|
migration_path = Rails.root.join(path).to_s
|
|
|
|
|
2021-10-18 20:10:29 -04:00
|
|
|
Find.find(migration_path).select { |m| migration_file_pattern.match? File.basename(m) }
|
2020-08-19 17:10:32 -04:00
|
|
|
end
|
|
|
|
end
|
2020-10-27 11:08:39 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def migration_folders
|
2020-11-12 22:09:15 -05:00
|
|
|
MIGRATION_FOLDERS
|
2020-10-27 11:08:39 -04:00
|
|
|
end
|
2020-08-19 17:10:32 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-05-11 17:10:21 -04:00
|
|
|
RequireMigration.prepend_mod_with('RequireMigration')
|
2020-11-12 22:09:15 -05:00
|
|
|
|
2020-08-19 17:10:32 -04:00
|
|
|
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
|