Advertisement
Guest User

Untitled

a guest
Jan 19th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. # Represents a person in an address book.
  2. class Contact
  3.  
  4. @@people = []
  5. attr_accessor :name, :email, :id
  6.  
  7. def initialize(id, name, email)
  8. @id = id
  9. @name = name
  10. @email = email
  11. end
  12.  
  13. # allows for upserting into contacts
  14. def save
  15. check = self.class.connect.exec_params('SELECT * FROM contacts WHERE id = $1', [id])
  16. if check.cmd_tuples == 0
  17. res = self.class.connect.exec_params(
  18. 'INSERT INTO contacts (name, email) VALUES ($1, $2) RETURNING id;',
  19. [name, email]
  20. )
  21. self.id = res[0]['id']
  22.  
  23. else
  24. self.class.connect.exec_params('UPDATE contacts SET name = $1, email = $2 WHERE id = $3::int;', [name, email, id])
  25. end
  26. end
  27.  
  28. # allows for deleting from contacts
  29. def destroy
  30. res = self.class.connect.exec_params('DELETE FROM contacts WHERE id = $1::int', [id])
  31. end
  32.  
  33. # Provides functionality for managing a list of Contacts in a database.
  34. class << self
  35.  
  36. def connect
  37. PG.connect(
  38. host: 'localhost',
  39. dbname: 'contact_list',
  40. user: 'development',
  41. password: 'development')
  42. end
  43.  
  44. # Returns an Array of Contacts loaded from the database.
  45. def all
  46. res = connect.exec_params('SELECT * FROM contacts;')
  47. list_contacts(res)
  48. end
  49.  
  50. # Creates a new contact, adding it to the database, returning the new contact.
  51. def create(name, email)
  52. raise DuplicateEmailError, "Duplicate email, cannot create this person" if all.detect {|contact| contact.email == email}
  53. new_person = Contact.new(nil, name, email)
  54. new_person.save
  55. new_person
  56. end
  57.  
  58. # Returns the contact with the specified id. If no contact has the id, returns nil.
  59. def find(id)
  60. res = connect.exec_params("SELECT * FROM contacts WHERE id = $1::int LIMIT 1;", [id])
  61. return nil if res.cmd_tuples == 0
  62. Contact.new(res[0]['id'], res[0]['name'], res[0]['email'])
  63. end
  64.  
  65. # Returns an array of contacts who match the given term.
  66. def search(term)
  67. res = connect.exec_params(
  68. "SELECT * FROM contacts WHERE email LIKE concat('%', $1::text, '%') OR name LIKE concat('%', $1::text, '%');",
  69. [term]
  70. )
  71. list_contacts(res)
  72. end
  73.  
  74. # Iterates over PG Result object and populates class variable @@people with relevant contacts
  75. def list_contacts(res)
  76. res.each do |contact|
  77. @@people << Contact.new(contact['id'].to_i, contact['name'], contact['email'])
  78. end
  79. @@people
  80. end
  81. end
  82. end
  83.  
  84. class DuplicateEmailError < StandardError
  85. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement