Class: ActiveRecord::LiteTable::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/vex/active_record/lite_table.rb

Constant Summary collapse

SHORTCUTS =
%w(primary_key string text integer float
decimal datetime timestamp time date binary boolean)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, options) ⇒ Validator

Returns a new instance of Validator.



8
9
10
11
# File 'lib/vex/active_record/lite_table.rb', line 8

def initialize(klass, options)
  @klass = klass
  @options = options
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



5
6
7
# File 'lib/vex/active_record/lite_table.rb', line 5

def klass
  @klass
end

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/vex/active_record/lite_table.rb', line 6

def options
  @options
end

Instance Method Details

#column(name, type, opts = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/vex/active_record/lite_table.rb', line 13

def column(name, type, opts = {})
  klass.silence do
    if !existing_column = klass.columns_hash[name.to_s]
      index_opt = opts.delete :index
      klass.connection.add_column(klass.table_name, name, type, opts)
      klass.reset_column_information

      index(name, :unique => (index_opt == :unique)) if index_opt 
      return
    end

    return if existing_column.type == type

    raise ColumnTypeMismatch, 
      "Column type mismatch on #{klass}##{name}: is #{existing_column.type}, but should be #{type}"
  end
end

#index(column_name, options = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/vex/active_record/lite_table.rb', line 58

def index(column_name, options={})
  begin
    klass.silence do
      klass.connection.add_index klass.table_name, column_name, options
    end
  rescue
    # TODO: It would be *great* to have a unique exception type here!
    # But even in this case we have to check the options for identity!
    case $!
    when ActiveRecord::StatementInvalid, SQLite3::SQLException
      return if $!.to_s =~ /Duplicate key name/       # for MySQL
      return if $!.to_s =~ /index .* already exists/  # for Sqlite3
      return if $!.to_s =~ /relation .* already exists/  # for Postgresql
    end
    
    raise
  end
end

#timestamps(*cols) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/vex/active_record/lite_table.rb', line 31

def timestamps(*cols)
  opts = cols.extract_options!
  cols = [ :created_at, :updated_at ] if cols.empty?

  index_opts = case index_opts = opts[:index]
  when Symbol then [ index_opts ]
  when Array  then index_opts
  when true   then [:created_at, :updated_at]
  else []
  end
  
  index_opts &= cols
  
  cols.each do |col|
    column(col, :datetime, :index => index_opts.include?(col))
  end
end