Class: Rmap::Database

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

Instance Method Summary collapse

Constructor Details

#initialize(connection = {}, &block) ⇒ Database

Returns a new instance of Database.



7
8
9
10
11
12
13
# File 'lib/rmap/database.rb', line 7

def initialize(connection={}, &block)
  self.connection = connection
  if !block.nil?
    instance_eval(&block)
  end
  @scopes = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



52
53
54
# File 'lib/rmap/database.rb', line 52

def method_missing name, *args
  Table.new(self, name)
end

Instance Method Details

#bindingsObject



35
36
37
# File 'lib/rmap/database.rb', line 35

def bindings
  binding
end

#clientObject



21
22
23
24
25
26
# File 'lib/rmap/database.rb', line 21

def client
  if @client.nil?
    @client = Mysql2::Client.new(@connection)
  end
  @client
end

#closeObject



28
29
30
31
32
33
# File 'lib/rmap/database.rb', line 28

def close
  if !@client.nil?
    @client.close
  end
  @client = nil
end

#commit_transactionObject



72
73
74
# File 'lib/rmap/database.rb', line 72

def commit_transaction
  client.query("commit")
end

#connection=(connection) ⇒ Object



15
16
17
18
19
# File 'lib/rmap/database.rb', line 15

def connection=(connection)
  @connection = {:host => "localhost", :username => "root", :password => ""}.merge connection
  close
  @table_names = nil
end

#create(name) ⇒ Object



56
57
58
59
# File 'lib/rmap/database.rb', line 56

def create(name)
  @table_names = nil
  client.query("create table `#{name}`(id int unsigned not null auto_increment primary key) engine = InnoDB")
end

#rollback_transactionObject



76
77
78
# File 'lib/rmap/database.rb', line 76

def rollback_transaction
  client.query("rollback")
end

#run(file_path = nil, &block) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/rmap/database.rb', line 39

def run(file_path = nil, &block)
  if !file_path.nil?
    instance_eval(::File.open(file_path).read, file_path)
  end
  if !block.nil?
    instance_eval(&block)
  end
end

#start_transactionObject



68
69
70
# File 'lib/rmap/database.rb', line 68

def start_transaction
  client.query("start transaction")
end

#table?(name) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/rmap/database.rb', line 48

def table?(name)
  table_names.include?(name.to_s)
end

#table_namesObject



61
62
63
64
65
66
# File 'lib/rmap/database.rb', line 61

def table_names
  if @table_names.nil?
    @table_names = client.query("show tables", :as => :array).map{|a| a[0]}
  end
  @table_names
end