-
-
Save natachaS/2cba23c39215dba53f6e 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
require 'sequel' | |
require 'pry' | |
class Artist | |
# CONN = PG.connect(dbname: 'chinook') | |
DB = Sequel.postgres('chinook') | |
attr_accessor *DB[:artists].columns | |
def self.new_from_row(row) | |
id = row[:id] | |
name = row[:name] | |
new(id, name) | |
end | |
# def self.find_by_name(name) | |
# result = table.where(name: name).all | |
# result.map do |row| | |
# self.new_from_row(row) | |
# end | |
# end | |
def self.find(id) | |
row = table.where(id: id).first | |
self.new_from_row(row) | |
end | |
def initialize(id, name) | |
@id = id | |
@name = name | |
end | |
def insert | |
@id = table.insert(name: self.name) | |
end | |
def update | |
table.where(id: self.id).update(name: name) | |
end | |
def save | |
if self.id | |
update | |
else | |
insert | |
end | |
end | |
def destroy | |
table.where(id: self.id).delete | |
end | |
def albums | |
sql = <<-SQL | |
SELECT * | |
FROM albums | |
WHERE artist_id=$1; | |
SQL | |
CONN.exec_params(sql, [self.id]).to_a | |
end | |
def method_missing(meth, *args, &block) | |
binding.pry | |
end | |
def self.method_missing(meth, *args) | |
if meth.to_s.match(/^find_by_/) | |
column = meth.to_s.split("find_by_")[-1] | |
query = args.first | |
result = table.where(column.to_sym => query).all | |
result.map do |row| | |
self.new_from_row(row) | |
end | |
else | |
super | |
end | |
end | |
private | |
def self.table | |
DB[:artists] | |
end | |
def table | |
DB[:artists] | |
end | |
end | |
# flim = Artist.new(nil, "Steven and the Flimflams") | |
# # Artist.find 270 | |
# flim.save | |
# # | |
# flim.name = "Steven and dropped tables" | |
# flim.save | |
# | |
# flim.destroy | |
result = Artist.find_by_name("Steven and rockets") | |
binding.pry | |
# reunion = Artist.find(281) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment