Created
October 21, 2016 17:08
-
-
Save anonymous/b465f88e57fe3c7bd3bded83297b6dcf 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, :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 |
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 "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