Class: SmartPrompt::DBAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_prompt/db_adapter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ DBAdapter

Returns a new instance of DBAdapter.



7
8
9
10
11
12
13
14
# File 'lib/smart_prompt/db_adapter.rb', line 7

def initialize(config)
  db_uri = config[:database]
  @db = Sequel.connect(db_uri)
  @tables = {}
  @db.tables.each do |table_name|
    define_table(table_name)
  end
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



6
7
8
# File 'lib/smart_prompt/db_adapter.rb', line 6

def db
  @db
end

#tablesObject (readonly)

Returns the value of attribute tables.



6
7
8
# File 'lib/smart_prompt/db_adapter.rb', line 6

def tables
  @tables
end

Instance Method Details

#define_table(table_name, class_name = table_name.to_s.capitalize) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/smart_prompt/db_adapter.rb', line 16

def define_table(table_name, class_name=table_name.to_s.capitalize)
  class_define = <<-EOT
    class #{class_name} < Sequel::Model(:#{table_name})
    end
  EOT
  eval(class_define)
  @tables[table_name] = eval(class_name)
end

#get_db_schemaObject



33
34
35
36
37
38
39
# File 'lib/smart_prompt/db_adapter.rb', line 33

def get_db_schema
  schema = {}
  @db.tables.each do |table_name|
    schema[table_name] = get_table_schema(table_name)
  end
  schema
end

#get_db_schema_strObject



41
42
43
# File 'lib/smart_prompt/db_adapter.rb', line 41

def get_db_schema_str
  JSON.pretty_generate(get_db_schema)
end

#get_table_schema(table_name) ⇒ Object



25
26
27
# File 'lib/smart_prompt/db_adapter.rb', line 25

def get_table_schema(table_name)
  @tables[table_name].db_schema
end

#get_table_schema_str(table_name) ⇒ Object



29
30
31
# File 'lib/smart_prompt/db_adapter.rb', line 29

def get_table_schema_str(table_name)
  JSON.pretty_generate(get_table_schema(table_name))
end