Sprankelprachtig aan/afmeldsysteem

person.rb 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # A person represents a human being. A Person may be a Member in one or more
  2. # Groups, and be a Participant in any number of events of those Groups.
  3. # A Person may access the system by creating a User, and may have at most one
  4. # User.
  5. class Person < ApplicationRecord
  6. # @!attribute first_name
  7. # @return [String]
  8. # the person's first name. ('Vincent' in 'Vincent van Gogh'.)
  9. #
  10. # @!attribute infix
  11. # @return [String]
  12. # the part of a person's surname that is not taken into account when
  13. # sorting by surname. ('van' in 'Vincent van Gogh'.)
  14. #
  15. # @!attribute last_name
  16. # @return [String]
  17. # the person's surname. ('Gogh' in 'Vincent van Gogh'.)
  18. #
  19. # @!attribute birth_date
  20. # @return [Date]
  21. # the person's birth date.
  22. #
  23. # @!attribute email
  24. # @return [String]
  25. # the person's email address.
  26. #
  27. # @!attribute is_admin
  28. # @return [Boolean]
  29. # whether or not the person has administrative rights.
  30. has_one :user
  31. has_many :members
  32. has_many :participants
  33. has_many :groups, through: :members
  34. has_many :activities, through: :participants
  35. validates :email, presence: true, uniqueness: true
  36. validates :first_name, presence: true
  37. validates :last_name, presence: true
  38. validate :birth_date_cannot_be_in_future
  39. before_validation :not_admin_if_nil
  40. before_save :update_user_email, if: :email_changed?
  41. # The person's full name.
  42. def full_name
  43. if self.infix
  44. [self.first_name, self.infix, self.last_name].join(' ')
  45. else
  46. [self.first_name, self.last_name].join(' ')
  47. end
  48. end
  49. # The person's reversed name, to sort by surname.
  50. def reversed_name
  51. if self.infix
  52. [self.last_name, self.infix, self.first_name].join(', ')
  53. else
  54. [self.last_name, self.first_name].join(', ')
  55. end
  56. end
  57. # All activities where this person is an organizer.
  58. def organized_activities
  59. self.participants.includes(:activity).where(is_leader: true)
  60. end
  61. private
  62. # Assert that the person's birth date, if any, lies in the past.
  63. def birth_date_cannot_be_in_future
  64. if self.birth_date && self.birth_date > Date.today
  65. errors.add(:birth_date, "can't be in the future.")
  66. end
  67. end
  68. # Explicitly force nil to false in the admin field.
  69. def not_admin_if_nil
  70. self.is_admin ||= false
  71. end
  72. # Ensure the person's user email is updated at the same time as the person's
  73. # email.
  74. def update_user_email
  75. if not self.user.nil?
  76. self.user.update!(email: self.email)
  77. end
  78. end
  79. end