Class: Konsierge::Generators::IdempotencyGenerator

Inherits:
Rails::Generators::NamedBase
  • Object
show all
Includes:
Rails::Generators::Migration
Defined in:
lib/generators/konsierge/idempotency_generator.rb

Constant Summary collapse

DEFAULT_COLUMN_KEY =
'idempotency_key'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.next_migration_number(_dirname) ⇒ Object



45
46
47
48
49
# File 'lib/generators/konsierge/idempotency_generator.rb', line 45

def self.next_migration_number(_dirname)
  @migration_number ||= Time.now.utc.strftime('%Y%m%d%H%M%S').to_i
  @migration_number += 1
  @migration_number.to_s
end

Instance Method Details

#create_migration_fileObject



16
17
18
# File 'lib/generators/konsierge/idempotency_generator.rb', line 16

def create_migration_file
  migration_template 'add_idempotency_column.rb.tt', "db/migrate/add_#{column_name}_to_#{table_name}.rb"
end

#update_modelObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/generators/konsierge/idempotency_generator.rb', line 20

def update_model
  unless File.exist?(model_full_path)
    say_status :skip, "Model file not found: #{model_path}", :yellow
    return
  end

  source = File.read(model_full_path)
  lines = []
  lines << "  include Idempotentable\n" unless source.match?(/^\s*include\s+Idempotentable\s*$/)

  unless default_key_column?
    if source.match?(/^\s*self\.idempotency_key_column\s*=\s*:.+$/)
      gsub_file model_path,
                /^\s*self\.idempotency_key_column\s*=\s*:.+$/,
                "  self.idempotency_key_column = :#{column_name}"
    else
      lines << "\n  self.idempotency_key_column = :#{column_name}\n"
    end
  end

  return if lines.empty?

  insert_into_file model_path, lines.join, after: /^\s*class\s+.+\n/
end