Module: KitDBSupport

Defined in:
lib/kit/db_support.rb

Class Method Summary collapse

Class Method Details

.connect(config) ⇒ Object

Establishes an ActiveRecord::Base connection.

Parameters:

  • config (Hash)

    settings for ActiveRecord::Base



49
50
51
# File 'lib/kit/db_support.rb', line 49

def self.connect config
  ActiveRecord::Base.establish_connection config
end

.create(*args) ⇒ Object



18
19
20
21
22
23
# File 'lib/kit/db_support.rb', line 18

def self.create *args
  begin
    create! *args
  rescue RuntimeError, /^Database file .+ exists.$/
  end
end

.create!(config) ⇒ Object

Create a database.

Parameters:

  • config (Hash)

    ActiveRecord::Base database configuration

Raises:

  • RuntimeError This will raise an exception if databse exists.



6
7
8
9
10
11
12
13
14
15
# File 'lib/kit/db_support.rb', line 6

def self.create! config
  case config[:adapter]
  when 'sqlite3'
    db_file = config[:database]
    raise RuntimeError, "Database file #{db_file} exists." if File.exists? db_file
    SQLite3::Database.new config[:database]
  else
    raise RuntimeError, "Creating database with adapter #{config[:adapter]} not supported."
  end
end

.destroy(*args) ⇒ Object



40
41
42
43
44
45
# File 'lib/kit/db_support.rb', line 40

def self.destroy *args
  begin
    destroy! *args
  rescue RuntimeError, /^Database file .+ does not exist.$/
  end
end

.destroy!(config) ⇒ Object

Destory a database.

Parameters:

  • config (Hash)

    ActiveRecord::Base database configuration

Raises:

  • RuntimeError This will raise an exception if databse does not exist.



28
29
30
31
32
33
34
35
36
37
# File 'lib/kit/db_support.rb', line 28

def self.destroy! config
  case config[:adapter]
  when 'sqlite3'
    db_file = config[:database]
    raise RuntimeError, "Database file #{db_file} does not exist." unless File.exists? db_file
    File.unlink db_file
  else
    raise RuntimeError, "Destroying database with adapter #{config[:adapter]} not supported."
  end
end

.migrate(path, direction = nil, steps = 1) ⇒ Object

Migrate up or down a given number of migrations.

Parameters:

  • path (String)

    location of migration files

  • direction (Symbol) (defaults to: nil)
  • steps (Integer) (defaults to: 1)


57
58
59
60
61
62
63
# File 'lib/kit/db_support.rb', line 57

def self.migrate path, direction = nil, steps = 1
  if direction.nil?
    ActiveRecord::Migrator.migrate(path, ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
  else
    ActiveRecord::Migrator.send direction, path, steps
  end
end

.migrate_to(path, version) ⇒ Object

Migrate to a specfic migration.

Parameters:

  • version (Integer)

    the migration number



68
69
70
# File 'lib/kit/db_support.rb', line 68

def self.migrate_to path, version
  ActiveRecord::Migrator.migrate(path, version)
end