Module: Velibe::Database

Includes:
Config
Defined in:
lib/velibe/db/database.rb

Constant Summary

Constants included from Config

Config::DATA_CSV, Config::DATA_CSV_FILE, Config::DB_NAME, Config::DB_PATH, Config::KV_NAME, Config::KV_PATH

Class Method Summary collapse

Class Method Details

.active_connectObject



20
21
22
# File 'lib/velibe/db/database.rb', line 20

def self.active_connect
  ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: DB_PATH.to_s
end

.connexionObject



35
36
37
38
39
# File 'lib/velibe/db/database.rb', line 35

def self.connexion
  return SQlite3::Database.new(DB_PATH.to_s)
  # §see:options
  # §maybe: delete?  [not that working?]
end

.createObject



24
25
26
27
28
# File 'lib/velibe/db/database.rb', line 24

def self.create
  active_connect
  make_schema
  populate
end

.create!Object



30
31
32
33
# File 'lib/velibe/db/database.rb', line 30

def self.create!
  prune
  create
end

.exist?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/velibe/db/database.rb', line 16

def self.exist?
  DB_PATH.exist? # §check
end

.make_schemaObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/velibe/db/database.rb', line 46

def self.make_schema
  ActiveRecord::Schema.define do

    create_table :stations do |t|
      t.integer :number
      t.string :name
      t.string :address
      t.float :latitude
      t.float :longitude
      t.index :number # ¤note: must be declared before
    end

    create_table :statuses do |t|
      t.integer :station_id
      t.boolean :status
      t.integer :bike_stands
      t.integer :available_bikes
      t.integer :available_bike_stands
      t.timestamp :last_update
    end

    # §todo: create others

  end
end

.populateObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/velibe/db/database.rb', line 72

def self.populate
  # MAYBE: Use fast cv
  # ¤see: stopwatch  > to bench creation. >> (but overkill since just one step operation)
  puts 'Populate Database from csv Station description'
  # ¤note: transaction for faster insert
  ActiveRecord::Base.transaction do
    CSV.foreach(DATA_CSV_FILE, headers: true, converters: :numeric) do |row|
      # §TODO: converter
      #  header_converters: :underscore -> tried but get: NoMethodError: undefined method `arity' for nil:NilClass
      Station.create(number: row['Number'], name: row['Name'], address: row['Address'],
                     latitude: row['Latitude'], longitude: row['Longitude'])
    end
  end
end

.pruneObject



41
42
43
# File 'lib/velibe/db/database.rb', line 41

def self.prune
  FileUtils.rm(DB_PATH) if self.exist?
end