Skip to content

Instantly share code, notes, and snippets.

@gregoire-bessagnet
Forked from anonymous/task.rb
Created October 23, 2016 14:49
Show Gist options
  • Save gregoire-bessagnet/4675da8260eaf99d85cf7c276702dcc8 to your computer and use it in GitHub Desktop.
Save gregoire-bessagnet/4675da8260eaf99d85cf7c276702dcc8 to your computer and use it in GitHub Desktop.
class Task
attr_reader :id, :title
attr_accessor :done
def initialize(args = {})
@id = args[:id]
@title = args[:title]
@description = args[:description]
@done = args[:done] || false
end
def save
if @id
DB.execute("UPDATE tasks SET title = ?, description = ?, done = ? WHERE id = ?", @title, @description, @done ? 1 : 0, @id)
else
query = <<SQL
INSERT INTO tasks (title, description, done) VALUES (?, ?, ?)
SQL
DB.execute(query, @title, @description, @done ? 1 : 0)
@id = DB.last_insert_row_id
end
end
#
def self.find(id)
DB.results_as_hash = true
rows = DB.execute("SELECT * FROM tasks WHERE id = ?", id)
row = rows.first
Task.build_task(row)
end
#
def self.all
DB.results_as_hash = true
rows = DB.execute("SELECT * FROM tasks")
return rows.map { |row| Task.build_task(row) }
end
def destroy
DB.execute("DELETE FROM tasks WHERE id = ?", @id)
end
#
private
def self.build_task(row)
Task.new(id: row['id'],
title: row['title'],
description: row['description'],
done: (row['done'] == 1)
)
end
end
require "sqlite3"
require "pry-byebug"
db_file_path = File.join(File.dirname(__FILE__), "tasks.db")
DB = SQLite3::Database.new(db_file_path)
# above lines must be kept
#
require_relative "task.rb"
# task = Task.new(title: "Faire la vaisselle", description: "Surtout bien frotter")
# task.save
# p task
# task = Task.find(10)
# p task
# task.destroy
#
tasks = Task.all
tasks.each do |task|
puts "#{task.id} - #{task.title}"
end
task = Task.find(11)
task.done = true
task.save
p task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment