Module: CNC::Migrator

Defined in:
lib/cnc/migrator.rb

Overview

Usage:

CNC::Migrator.listen if Rails.env.development?

Class Method Summary collapse

Class Method Details

.fresh_migration(name) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/cnc/migrator.rb', line 19

def fresh_migration(name)
  <<~RUBY
    class #{name.camelize} < ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]
      def change
        #{yield if block_given?}
      end
    end
  RUBY
end

.listenObject



44
45
46
47
48
49
50
51
# File 'lib/cnc/migrator.rb', line 44

def listen
  log "Watching for unstamped migration files in #{path}."
  Listen.to(path, only:, relative: true) do |modified, added, removed|
    process(added | modified)
  end.start
rescue Errno::ENOENT
  log "db/ directory does not exist."
end

.logObject



14
# File 'lib/cnc/migrator.rb', line 14

def log(...) = logger.info(...)

.loggerObject



10
11
12
# File 'lib/cnc/migrator.rb', line 10

def logger
  @logger ||= ActiveSupport::TaggedLogging.new(Rails.logger).tagged("CNC::Migrator")
end

.onlyObject



17
# File 'lib/cnc/migrator.rb', line 17

def only = %r{(migrate/)([a-z]\w+)\.rb$}

.pathObject



16
# File 'lib/cnc/migrator.rb', line 16

def path = Rails.root / "db"

.process(paths) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cnc/migrator.rb', line 29

def process(paths)
  number = Time.now.utc.strftime("%Y%m%d%H%M%S")
  paths.each do |path|
    body = File.read(path)
    new_path = path.sub(only, "\\1#{number}_\\2.rb")
    log "Moving '#{path}' to '#{new_path}'."

    File.rename(path, new_path)
    File.open(new_path, "w+") do |file|
      file << fresh_migration($2)  { body }
    end
    number.succ!
  end
end