has_group_relation_definition.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module HasGroupRelationDefinition
  3. extend ActiveSupport::Concern
  4. included do
  5. self.table_name = "groups_#{group_relation_model_identifier}s"
  6. self.primary_keys = ref_key, :group_id, :access
  7. belongs_to group_relation_model_identifier
  8. belongs_to :group
  9. validates :access, presence: true
  10. validate :validate_access
  11. after_save :touch_related
  12. after_destroy :touch_related
  13. end
  14. private
  15. def group_relation_instance
  16. @group_relation_instance ||= send(group_relation_model_identifier)
  17. end
  18. def group_relation_model_identifier
  19. @group_relation_model_identifier ||= self.class.group_relation_model_identifier
  20. end
  21. def touch_related
  22. # rubocop:disable Rails/SkipsModelValidations
  23. group.touch if group&.persisted?
  24. group_relation_instance.touch if group_relation_instance&.persisted?
  25. # rubocop:enable Rails/SkipsModelValidations
  26. end
  27. def validate_access
  28. query = self.class.where(
  29. group_relation_model_identifier => group_relation_instance,
  30. group: group
  31. )
  32. query = if access == 'full'
  33. query.where.not(access: 'full')
  34. else
  35. query.where(access: 'full')
  36. end
  37. return if !query.exists?
  38. errors.add(:access, "#{group_relation_model_identifier.to_s.capitalize} can have full or granular access to group")
  39. end
  40. # methods defined here are going to extend the class, not the instance of it
  41. class_methods do
  42. def group_relation_model_identifier
  43. @group_relation_model_identifier ||= model_name.singular.split('_').first.to_sym
  44. end
  45. def ref_key
  46. @ref_key ||= "#{group_relation_model_identifier}_id".to_sym
  47. end
  48. end
  49. end