Class: CtoD::DB

Inherits:
Object
  • Object
show all
Includes:
ActiveSupport::Inflector
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.



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

def initialize(csv, uri, string_size:100)
  @table_name = File.basename(csv, '.csv').intern
  @class_name = singularize(@table_name).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.



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

def class_name
  @class_name
end

#string_sizeObject

Returns the value of attribute string_size.



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

def string_size
  @string_size
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



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

def table_name
  @table_name
end

#uriObject (readonly)

Returns the value of attribute uri.



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

def uri
  @uri
end

Class Method Details

.connect(uri) ⇒ Object



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

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



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

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



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

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)


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

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