Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Represents a person in an address book.
- class Contact
- @@people = []
- attr_accessor :name, :email, :id
- def initialize(id, name, email)
- @id = id
- @name = name
- @email = email
- end
- # allows for upserting into contacts
- def save
- check = self.class.connect.exec_params('SELECT * FROM contacts WHERE id = $1', [id])
- if check.cmd_tuples == 0
- res = self.class.connect.exec_params(
- 'INSERT INTO contacts (name, email) VALUES ($1, $2) RETURNING id;',
- [name, email]
- )
- self.id = res[0]['id']
- else
- self.class.connect.exec_params('UPDATE contacts SET name = $1, email = $2 WHERE id = $3::int;', [name, email, id])
- end
- end
- # allows for deleting from contacts
- def destroy
- res = self.class.connect.exec_params('DELETE FROM contacts WHERE id = $1::int', [id])
- end
- # Provides functionality for managing a list of Contacts in a database.
- class << self
- def connect
- PG.connect(
- host: 'localhost',
- dbname: 'contact_list',
- user: 'development',
- password: 'development')
- end
- # Returns an Array of Contacts loaded from the database.
- def all
- res = connect.exec_params('SELECT * FROM contacts;')
- list_contacts(res)
- end
- # Creates a new contact, adding it to the database, returning the new contact.
- def create(name, email)
- raise DuplicateEmailError, "Duplicate email, cannot create this person" if all.detect {|contact| contact.email == email}
- new_person = Contact.new(nil, name, email)
- new_person.save
- new_person
- end
- # Returns the contact with the specified id. If no contact has the id, returns nil.
- def find(id)
- res = connect.exec_params("SELECT * FROM contacts WHERE id = $1::int LIMIT 1;", [id])
- return nil if res.cmd_tuples == 0
- Contact.new(res[0]['id'], res[0]['name'], res[0]['email'])
- end
- # Returns an array of contacts who match the given term.
- def search(term)
- res = connect.exec_params(
- "SELECT * FROM contacts WHERE email LIKE concat('%', $1::text, '%') OR name LIKE concat('%', $1::text, '%');",
- [term]
- )
- list_contacts(res)
- end
- # Iterates over PG Result object and populates class variable @@people with relevant contacts
- def list_contacts(res)
- res.each do |contact|
- @@people << Contact.new(contact['id'].to_i, contact['name'], contact['email'])
- end
- @@people
- end
- end
- end
- class DuplicateEmailError < StandardError
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement