module DuyojiTodo::DB

データベースへの接続処理を扱うモジュール @author Tsuyoshi Maeda

Public Class Methods

prepare() click to toggle source

データベースへの接続とテーブルの作成を行う @return [void]

# File lib/duyoji_todo/db.rb, line 15
def self.prepare
        database_path = File.join(ENV['HOME'], '.duyoji_todo', 'duyoji_todo.sqlite3')

        connect_database database_path
        create_table_if_not_exists database_path
end

Private Class Methods

connect_database(path) click to toggle source
# File lib/duyoji_todo/db.rb, line 22
def self.connect_database(path)
        spec = {adapter: 'sqlite3', database: path}
        ActiveRecord::Base.establish_connection spec
end
create_database_path(path) click to toggle source
# File lib/duyoji_todo/db.rb, line 45
def self.create_database_path(path)
        FileUtils.mkdir_p File.dirname(path)
end
create_table_if_not_exists(path) click to toggle source
# File lib/duyoji_todo/db.rb, line 27
def self.create_table_if_not_exists(path)
        create_database_path path

        connection = ActiveRecord::Base.connection

        return if connection.table_exists?(:tasks)


        connection.create_table :tasks do |t|
                t.column :name,    :string,  null: false
                t.column :content, :text,    null: false
                t.column :status,  :integer, default: 0, null: false
                t.timestamps
        end
        connection.add_index :tasks, :status
        connection.add_index :tasks, :created_at
end