user_roles.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # frozen_string_literal: true
  2. module UserRoles
  3. extend ActiveSupport::Concern
  4. included do
  5. scope :admins, -> { where(admin: true) }
  6. scope :moderators, -> { where(moderator: true) }
  7. scope :staff, -> { admins.or(moderators) }
  8. end
  9. def staff?
  10. admin? || moderator?
  11. end
  12. def role=(value)
  13. case value
  14. when 'admin'
  15. self.admin = true
  16. self.moderator = false
  17. when 'moderator'
  18. self.admin = false
  19. self.moderator = true
  20. else
  21. self.admin = false
  22. self.moderator = false
  23. end
  24. end
  25. def role
  26. if admin?
  27. 'admin'
  28. elsif moderator?
  29. 'moderator'
  30. else
  31. 'user'
  32. end
  33. end
  34. def role?(role)
  35. case role
  36. when 'user'
  37. true
  38. when 'moderator'
  39. staff?
  40. when 'admin'
  41. admin?
  42. else
  43. false
  44. end
  45. end
  46. def promote!
  47. if moderator?
  48. update!(moderator: false, admin: true)
  49. elsif !admin?
  50. update!(moderator: true)
  51. end
  52. end
  53. def demote!
  54. if admin?
  55. update!(admin: false, moderator: true)
  56. elsif moderator?
  57. update!(moderator: false)
  58. end
  59. end
  60. end