Created
January 19, 2016 23:51
-
-
Save j0ni/6a799c323c488972ae79 to your computer and use it in GitHub Desktop.
An example ORM-like contact class
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 'pg' | |
class Contact | |
attr_reader :id, :name, :email | |
class << self | |
def connection | |
@@conn ||= PG.connect( | |
dbname: 'contact_list', | |
user: 'yorname', | |
host: 'localhost' | |
) | |
end | |
def all | |
connection.exec("select * from contacts;").map do |row| | |
Contact.new(row["id"], row["name"], row["email"]) | |
end | |
end | |
end | |
def initialize(id, name, email) | |
@id = id | |
@name = name | |
@email = email | |
end | |
def to_s | |
"#{id}: #{name}, \"#{email}\"" | |
end | |
end | |
puts Contact.all |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment