Class: Facemock::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/facemock/database.rb,
lib/facemock/database/table.rb

Defined Under Namespace

Classes: Table

Constant Summary collapse

ADAPTER =
"sqlite3"
DB_DIRECTORY =
File.expand_path("../../../db", __FILE__)
DEFAULT_DB_NAME =
"facemock"
TABLE_NAMES =
[:applications, :users, :permissions, :authorization_codes]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil) ⇒ Database

Returns a new instance of Database.



14
15
16
17
18
# File 'lib/facemock/database.rb', line 14

def initialize(name=nil)
  @name = DEFAULT_DB_NAME
  connect
  create_tables
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



12
13
14
# File 'lib/facemock/database.rb', line 12

def connection
  @connection
end

#nameObject (readonly)

Returns the value of attribute name.



11
12
13
# File 'lib/facemock/database.rb', line 11

def name
  @name
end

Instance Method Details

#clearObject



42
43
44
45
# File 'lib/facemock/database.rb', line 42

def clear
  drop_tables
  create_tables
end

#connectObject



20
21
22
23
24
# File 'lib/facemock/database.rb', line 20

def connect
  @connection = SQLite3::Database.new filepath
  @state = :connected
  @connection
end

#connected?Boolean

Returns:

  • (Boolean)


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

def connected?
  @state == :connected
end

#create_tablesObject



47
48
49
50
51
52
# File 'lib/facemock/database.rb', line 47

def create_tables
  TABLE_NAMES.each do |table_name|
    self.send "create_#{table_name}_table" unless table_exists?(table_name)
  end
  true
end

#disconnect!Object



26
27
28
29
30
# File 'lib/facemock/database.rb', line 26

def disconnect!
  @connection.close
  @state = :disconnected
  nil
end

#dropObject



36
37
38
39
40
# File 'lib/facemock/database.rb', line 36

def drop
  disconnect!
  File.delete(filepath) if File.exist?(filepath)
  nil
end

#drop_table(table_name) ⇒ Object



54
55
56
57
58
# File 'lib/facemock/database.rb', line 54

def drop_table(table_name)
  return false unless File.exist?(filepath) && table_exists?(table_name)
  @connection.execute "drop table #{table_name};"
  true
end

#drop_tablesObject



60
61
62
63
64
# File 'lib/facemock/database.rb', line 60

def drop_tables
  return false unless File.exist?(filepath)
  TABLE_NAMES.each{|table_name| drop_table(table_name) }
  true
end

#filepathObject



66
67
68
69
# File 'lib/facemock/database.rb', line 66

def filepath
  name ||= @name
  File.join(DB_DIRECTORY, "#{@name}.#{ADAPTER}")
end

#table_exists?(table_name) ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
74
75
76
77
# File 'lib/facemock/database.rb', line 71

def table_exists?(table_name)
  tables = @connection.execute "select * from sqlite_master"
  tables.each do |table|
    return true if table[1].to_s == table_name.to_s
  end
  false
end