Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. class Doctor
  2. attr_reader :id
  3. attr_accessor :name, :age, :specialty
  4.  
  5. def initialize(attributes={})
  6. @id = attributes[:id]
  7. @name = attributes[:name]
  8. @age = attributes[:age]
  9. @specialty = attributes[:specialty]
  10. end
  11.  
  12. def save
  13. @id.nil? ? insert : update
  14. end
  15.  
  16. def destroy
  17. DB.execute('DELETE FROM doctors WHERE id = ?', @id)
  18. end
  19.  
  20. def self.find(id)
  21. DB.results_as_hash = true
  22. row = DB.execute('SELECT * FROM doctors WHERE id = ?', id).first
  23. Doctor.new(name: row['name'], id: row['id'] , age: row['age'], specialty: row['specialty'])
  24. end
  25.  
  26. def self.all
  27. DB.results_as_hash = true
  28. rows = DB.execute('SELECT * FROM doctors')
  29. result = []
  30. rows.each do |row|
  31. result << Doctor.new(name: row['name'], id: row['id'] , age: row['age'], specialty: row['specialty'])
  32. end
  33. result
  34. end
  35.  
  36. private
  37. def insert
  38. DB.execute("INSERT INTO doctors (name, age, specialty) VALUES (?,?,?)", @name, @age, @specialty)
  39. @id = DB.last_insert_row_id
  40. end
  41.  
  42. def update
  43. DB.execute("UPDATE doctors SET name=?, age=?, specialty=? WHERE id=?", @name, @age, @specialty, @id)
  44. end
  45.  
  46.  
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement