Class: Slick::Database::Column

Inherits:
Object
  • Object
show all
Defined in:
lib/slick/database/column.rb

Constant Summary collapse

TYPE_TO_MYSQL_COLUMN_TYPE_MAP =
{
    "primary_key" => "int(11) unsigned",
    "foreign_key" => "int(11) unsigned",
    "binary" => "longblob",
    "boolean" => "enum('false','true')",
    "date" => "date",
    "datetime" => "datetime",
    "decimal" => "decimal",
    "float" => "float",
    "integer" => "int(11)",
    "string" => "varchar(255)",
    "text" => "longtext",
    "time" => "time",
    "timestamp" => "datetime"
}
MYSQL_COLUMN_TYPE_TO_TYPE_MAP =
TYPE_TO_MYSQL_COLUMN_TYPE_MAP.invert

Instance Method Summary collapse

Constructor Details

#initialize(table, name, type = nil) ⇒ Column

Returns a new instance of Column.



22
23
24
25
26
# File 'lib/slick/database/column.rb', line 22

def initialize(table, name, type = nil)
    @table = table
    @name = name
    @type = type
end

Instance Method Details

#create(type = 'string', options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/slick/database/column.rb', line 36

def create(type = 'string', options = {})
    type = type.to_s
    options = {:index => type == 'foreign_key'}.paramify.merge(options)
    database = @table.instance_variable_get(:@database)

    @table.create

    database.run(
        'alter table ?', @table.class.name.to_sym,
        'add column ?', @name.to_sym, TYPE_TO_MYSQL_COLUMN_TYPE_MAP[type]
    ) if !exist?

    database.run(
        'alter table ?', @table.class.name.to_sym,
        'add index(?)', @name.to_sym
    ) if options['index'] == 'true'
end

#dropObject



54
55
56
57
58
59
60
61
62
# File 'lib/slick/database/column.rb', line 54

def drop
    database = @table.instance_variable_get(:@database)

    database.run(
        'alter table ?', @table.class.name.to_sym,
        'drop ?', @name.to_sym
    )
    @type = nil
end

#exist?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/slick/database/column.rb', line 32

def exist?
    !type.nil?
end

#typeObject



28
29
30
# File 'lib/slick/database/column.rb', line 28

def type
    @type ||= @table.send(@name).instance_variable_get(:@type)
end