Skip to content

Instantly share code, notes, and snippets.

Created June 4, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/c9683828c013002a9848 to your computer and use it in GitHub Desktop.
Save anonymous/c9683828c013002a9848 to your computer and use it in GitHub Desktop.
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