Created
May 7, 2021 16:59
-
-
Save Oceantidote/d9cf5f4f5d190f0bc06b0e62fe14def3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Task | |
attr_reader :id | |
attr_accessor :title, :description, :done | |
def initialize(attr = {}) | |
@id = attr[:id] | |
@title = attr[:title] | |
@done = attr[:done] || false | |
@description = attr[:description] | |
end | |
def self.find(id) | |
result = DB.execute("SELECT * FROM tasks WHERE id = ?", id).first | |
build_task(result) if result | |
end | |
def self.all | |
tasks = DB.execute("SELECT * FROM tasks") | |
tasks.map{ |result| build_task(result) } | |
end | |
def destroy | |
DB.execute("DELETE FROM tasks WHERE id = ?", @id) | |
end | |
def save | |
if @id | |
DB.execute("UPDATE tasks SET title = ?, description = ?, done = ? WHERE id = ?", | |
@title, @description, @done ? 1 : 0, @id) | |
else | |
DB.execute("INSERT INTO tasks (title, description, done) VALUES (?,?,?)", | |
@title, @description, @done ? 1 : 0) | |
@id = DB.last_insert_row_id | |
end | |
end | |
def self.build_task(result) | |
Task.new( | |
id: result['id'], | |
title: result['title'], | |
description: result['description'], | |
done: result['done'] == 1 | |
) | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "sqlite3" | |
require_relative "task" | |
DB = SQLite3::Database.new("tasks.db") | |
DB.results_as_hash = true | |
# find should return a given post | |
# expect to put out an instance of task with the following data | |
# 1|Complete Livecode|Implement CRUD on Task|false | |
p Task.find(1) | |
# return array of instances of task | |
p Task.all | |
# 1 save a new task to the database | |
new_task = Task.new(title: 'hello', description: 'more beer please') | |
new_task.save | |
# expect the task to have an id | |
p new_task.id | |
# 2 use save to update an existing task | |
to_update = Task.find(new_task.id) | |
to_update.title = "refill" | |
to_update.save | |
# expect the task to have been updated and to see a true below | |
p Task.find(new_task.id).title == 'refill' | |
# destroy the task we just created | |
Task.find(new_task.id).destroy | |
# expect Task.find(new_task.id) to be nil | |
p Task.find(new_task.id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment