class Lhm::ColumnWithSql

Abstracts the details of a table column definition when specified with a MySQL column definition string

Attributes

definition[R]
name[R]

Public Class Methods

column_factory() click to toggle source

Returns the column's class to be used

@return [Constant]

# File lib/lhm/column_with_sql.rb, line 12
def self.column_factory
  ::ActiveRecord::ConnectionAdapters::DepartureAdapter::Column
end
new(name, definition) click to toggle source

Constructor

@param name [String, Symbol] @param definition [String]

# File lib/lhm/column_with_sql.rb, line 20
def initialize(name, definition)
  @name = name
  @definition = definition
end

Public Instance Methods

attributes() click to toggle source

Returns the column data as an Array to be used with the splat operator. See Lhm::Adaper#add_column

@return [Array]

# File lib/lhm/column_with_sql.rb, line 29
def attributes
  [type, column_options]
end

Private Instance Methods

column() click to toggle source

Returns the column instance with the provided data

@return [column_factory]

# File lib/lhm/column_with_sql.rb, line 54
def column
  cast_type = ActiveRecord::Base.connection.send(:lookup_cast_type, definition)
  metadata = ActiveRecord::ConnectionAdapters::SqlTypeMetadata.new(
    type: cast_type.type,
    sql_type: definition,
    limit: cast_type.limit
  )
  mysql_metadata = ActiveRecord::ConnectionAdapters::MySQL::TypeMetadata.new(metadata)
  @column ||= self.class.column_factory.new(
    name,
    default_value,
    mysql_metadata,
    null_value
  )
end
column_options() click to toggle source

TODO: investigate

Rails doesn't take into account lenght argument of INT in the definition, as an integer it will default it to 4 not an integer

Returns the columns data as a Hash

@return [Hash]

# File lib/lhm/column_with_sql.rb, line 47
def column_options
  { limit: column.limit, default: column.default, null: column.null }
end
default_value() click to toggle source

Gets the DEFAULT value the column takes as specified in the definition, if any

@return [String, NilClass]

# File lib/lhm/column_with_sql.rb, line 74
def default_value
  match = if definition =~ /timestamp|datetime/i
            /default '?(.+[^'])'?/i.match(definition)
          else
            /default '?(\w+)'?/i.match(definition)
          end

  return unless match

  match[1].downcase != 'null' ? match[1] : nil
end
null_value() click to toggle source

Checks whether the column accepts NULL as specified in the definition

@return [Boolean]

# File lib/lhm/column_with_sql.rb, line 89
def null_value
  match = /((\w*) NULL)/i.match(definition)
  return true unless match

  match[2].downcase == 'not' ? false : true
end