summaryrefslogtreecommitdiff
path: root/spec/support/helpers/require_migration.rb
blob: de3a8a81ab5c3ff782ed72c2607baa2086ac2e90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

require 'find'

class RequireMigration
  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
  SPEC_FILE_PATTERN = %r{.+/(?<file_name>.+)_spec\.rb}.freeze

  class << self
    def require_migration!(file_name)
      file_paths = search_migration_file(file_name)
      raise AutoLoadError, file_name unless file_paths.first

      require file_paths.first
    end

    def search_migration_file(file_name)
      migration_folders.flat_map do |path|
        migration_path = Rails.root.join(path).to_s

        Find.find(migration_path).select { |m| File.basename(m).match? /\A\d+_#{file_name}\.rb\z/ }
      end
    end

    private

    def migration_folders
      MIGRATION_FOLDERS
    end
  end
end

RequireMigration.prepend_mod_with('RequireMigration')

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