class Shaf::Generator::Migration::Type

Attributes

alter_template[R]
create_template[R]
name[R]
validator[R]

Public Class Methods

new(str, create_template:, alter_template:, validator: nil) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 7
def initialize(str, create_template:, alter_template:, validator: nil)
  @name = str.downcase.to_sym
  @create_template = create_template.freeze
  @alter_template = alter_template.freeze
  @validator = validator.freeze
  freeze
end

Public Instance Methods

==(other) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 60
def ==(other)
  name == other.name
end
build(str, create: false, alter: false) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 15
def build(str, create: false, alter: false)
  args = parse_args(str)
  validate!(*args)

  if create && !alter
    build_create_string(*args)
  elsif alter && !create
    build_alter_string(*args)
  else
    [
      build_create_string(*args),
      build_alter_string(*args)
    ]
  end
end
build_alter_string(*args) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 45
def build_alter_string(*args)
  format alter_template, *args
rescue ArgumentError
  raise Command::ArgumentError,
    "Wrong number of arguments for type #{name} with string " \
    "template '#{alter_template}. Given: #{args}"
end
build_create_string(*args) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 37
def build_create_string(*args)
  format create_template, *args
rescue ArgumentError
  raise Command::ArgumentError,
    "Wrong number of arguments for type #{name} with string " \
    "template '#{create_template}. Given: #{args}"
end
parse_args(str) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 31
def parse_args(str)
  name, col_type  = str.to_s.downcase.split(':')
  _, *args = col_type&.split(',')
  args.unshift name
end
validate!(*args) click to toggle source
# File lib/shaf/generator/migration/type.rb, line 53
def validate!(*args)
  errors = Array(validator&.call(name, *args))
  return if errors.empty?

  raise "Failed to process '#{name}': #{errors&.join(', ')}"
end