You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.3 KiB
41 lines
1.3 KiB
class Fruit
|
|
if(ENV['DATABASE_URL'])
|
|
uri = URI.parse(ENV['DATABASE_URL'])
|
|
DB = PG.connect(uri.hostname, uri.port, nil, nil, uri.path[1..-1], uri.user, uri.password)
|
|
else
|
|
DB = PG.connect(host: "localhost", port: 5432, dbname: 'simplerails')
|
|
end
|
|
|
|
def initialize(opts = {})
|
|
@id = opts["id"].to_i
|
|
@name = opts["name"]
|
|
@color = opts["color"]
|
|
@readyToEat = (opts["readytoeat"]=='t')?true:false
|
|
end
|
|
|
|
def self.all
|
|
results = DB.exec("SELECT * FROM fruits;")
|
|
return results.map { |fruit_opts| Fruit.new(fruit_opts)}
|
|
end
|
|
|
|
def self.find(id)
|
|
results = DB.exec("SELECT * FROM fruits WHERE id=#{id};")
|
|
return Fruit.new(results.first)
|
|
end
|
|
|
|
def self.create(opts={})
|
|
results = DB.exec("INSERT INTO fruits (name, color, readytoeat) VALUES ( '#{opts["name"]}', '#{opts["color"]}', #{opts["readyToEat"]} );")
|
|
return { created: true }
|
|
end
|
|
|
|
def self.delete(id)
|
|
results = DB.exec("DELETE FROM fruits WHERE id=#{id};")
|
|
return { deleted: true }
|
|
end
|
|
|
|
def self.update(id, opts={})
|
|
results = DB.exec("UPDATE fruits SET name='#{opts["name"]}', color='#{opts["color"]}', readytoeat=#{opts["readyToEat"]} WHERE id=#{id} ;")
|
|
return { updated: true }
|
|
end
|
|
end
|