Sha256: 9699a4180123734c492377594387a26d459b872faaee667695a8a0970c8d7331

Contents?: true

Size: 1.48 KB

Versions: 2

Compression:

Stored size: 1.48 KB

Contents

require 'fileutils'
require 'active_record'

module Ds
  module DB
    def self.prepare
      database_path = File.join(ENV['HOME'], '.ds', 'ds.sqlite3')

      connect_database database_path
      create_deeds_table_if_not_exists database_path
      create_timestamps_table_if_not_exists database_path
    end

    def self.connect_database(path)
      spec = { adapter: 'sqlite3', database: path }
      ActiveRecord::Base.establish_connection spec
    end

    def self.create_deeds_table_if_not_exists(path)
      create_database_path path

      connection = ActiveRecord::Base.connection

      return if connection.table_exists?(:deeds)

      connection.create_table :deeds do |t|
        t.column :content, :text,   null: false
        t.column :hour,    :float,  null: false
        t.timestamps
      end

      connection.add_index :deeds, :created_at
    end

    def self.create_timestamps_table_if_not_exists(path)
      create_database_path path

      connection = ActiveRecord::Base.connection

      return if connection.table_exists?(:timestamps)

      connection.create_table :timestamps do |t|
        t.references :deed, foreign_key: true
        t.timestamps
      end

      connection.add_index :timestamps, [:deed_id, :created_at]
    end

    def self.create_database_path(path)
      FileUtils.mkdir_p File.dirname(path)
    end

    private_class_method :connect_database, :create_deeds_table_if_not_exists, :create_timestamps_table_if_not_exists, :create_database_path
  end
end

Version data entries

2 entries across 1 versions & 1 rubygems

Version Path
mdg-1.0.1 vendor/bundle/ruby/2.3.0/gems/ds-0.0.2/lib/ds/db.rb
mdg-1.0.1 vendor/bundle/ruby/2.3.0/gems/ds-0.0.3/lib/ds/db.rb