Class: DeclareSchema::SchemaChange::TableAdd

Inherits:
Base
  • Object
show all
Defined in:
lib/declare_schema/schema_change/table_add.rb

Instance Method Summary collapse

Methods inherited from Base

#down, format_options, #up

Constructor Details

#initialize(table_name, fields, create_table_options, sql_options: nil) ⇒ TableAdd

Returns a new instance of TableAdd.



8
9
10
11
12
13
14
15
16
# File 'lib/declare_schema/schema_change/table_add.rb', line 8

def initialize(table_name, fields, create_table_options, sql_options: nil)
  @table_name = table_name
  fields.all? do |type, name, options|
    type.is_a?(Symbol) && name.is_a?(Symbol) && options.is_a?(Hash)
  end or raise ArgumentError, "fields must be Array(Array(Symbol, Symbol, Hash)); got #{fields.inspect}"
  @fields = fields
  @create_table_options = create_table_options
  @create_table_options = @create_table_options.merge(options: sql_options) if sql_options.present?
end

Instance Method Details

#down_commandObject



32
33
34
# File 'lib/declare_schema/schema_change/table_add.rb', line 32

def down_command
  "drop_table #{@table_name.to_sym.inspect}"
end

#up_commandObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/declare_schema/schema_change/table_add.rb', line 18

def up_command
  longest_field_type_length = @fields.map { |type, _name, _option| type.to_s.length }.max

  <<~EOS.strip
    create_table #{[@table_name.to_sym.inspect, *self.class.format_options(@create_table_options)].join(', ')} do |t|
    #{@fields.map do |type, name, options|
        padded_type = format("%-*s", longest_field_type_length, type)
        args = [name.inspect, *self.class.format_options(options)].join(', ')
        "  t.#{padded_type} #{args}"
      end.join("\n")}
    end
  EOS
end