Class: CtoD::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/ctoD/db.rb

Constant Summary collapse

AR =
ActiveRecord::Base

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv, uri, string_size: 100) ⇒ DB

Returns a new instance of DB.



10
11
12
13
14
15
16
# File 'lib/ctoD/db.rb', line 10

def initialize(csv, uri, string_size:100)
  @table_name = File.basename(csv, '.csv').intern
  @class_name = @table_name[0..-2].capitalize
  @csv = CSV.table(csv)
  @string_size = string_size
  @uri = DB.connect(uri)
end

Instance Attribute Details

#class_nameObject (readonly)

Returns the value of attribute class_name.



9
10
11
# File 'lib/ctoD/db.rb', line 9

def class_name
  @class_name
end

#string_sizeObject

Returns the value of attribute string_size.



8
9
10
# File 'lib/ctoD/db.rb', line 8

def string_size
  @string_size
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



9
10
11
# File 'lib/ctoD/db.rb', line 9

def table_name
  @table_name
end

#uriObject (readonly)

Returns the value of attribute uri.



9
10
11
# File 'lib/ctoD/db.rb', line 9

def uri
  @uri
end

Class Method Details

.connect(uri) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ctoD/db.rb', line 41

def self.connect(uri)
  uri = URI.parse(uri)
  uri.scheme = 'postgresql' if uri.scheme=='postgres'
  settings = {
    adapter: uri.scheme,
    host: uri.host,
    username: uri.user,
    password: uri.password,
    database: uri.path[1..-1],
    encoding: 'utf8'
  }
  AR.establish_connection(settings)
  uri
rescue => e
  puts "Something go wrong at connect: #{e}"
end

Instance Method Details

#create_tableObject



24
25
26
27
28
29
30
31
32
# File 'lib/ctoD/db.rb', line 24

def create_table
  conn = AR.connection
  conn.create_table(@table_name) do |t|
    @csv.headers.zip(column_types).each do |name, type|
      t.column name, type
    end
    t.timestamps
  end
end

#exportObject



34
35
36
37
38
39
# File 'lib/ctoD/db.rb', line 34

def export
  self.class.const_set(@class_name, Class.new(AR))
  self.class.const_get(@class_name).create! @csv.map(&:to_hash)
rescue => e
  puts "Something go wrong at export: #{e}"
end

#table_exists?Boolean

Returns:

  • (Boolean)


18
19
20
21
22
# File 'lib/ctoD/db.rb', line 18

def table_exists?
  AR.connection.table_exists?(@table_name)
rescue => e
  puts e
end