has_tags.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module HasTags
  3. extend ActiveSupport::Concern
  4. included do
  5. before_destroy :tag_destroy
  6. end
  7. =begin
  8. add an tag to model
  9. model = Model.find(123)
  10. model.tag_add(name)
  11. =end
  12. def tag_add(name, current_user_id = nil, sourceable: nil)
  13. Tag.tag_add(
  14. object: self.class.to_s,
  15. o_id: id,
  16. item: name,
  17. created_by_id: current_user_id,
  18. sourceable: sourceable,
  19. )
  20. end
  21. =begin
  22. remove an tag of model
  23. model = Model.find(123)
  24. model.tag_remove(name)
  25. =end
  26. def tag_remove(name, current_user_id = nil, sourceable: nil)
  27. Tag.tag_remove(
  28. object: self.class.to_s,
  29. o_id: id,
  30. item: name,
  31. created_by_id: current_user_id,
  32. sourceable: sourceable,
  33. )
  34. end
  35. =begin
  36. update tags of model
  37. model = Model.find(123)
  38. model.tag_update(['name', 'tag'])
  39. =end
  40. def tag_update(items, current_user_id = nil)
  41. Tag.tag_update(
  42. object: self.class.to_s,
  43. o_id: id,
  44. items: items,
  45. created_by_id: current_user_id,
  46. )
  47. end
  48. =begin
  49. tag list of model
  50. model = Model.find(123)
  51. tags = model.tag_list
  52. =end
  53. def tag_list
  54. Tag.tag_list(
  55. object: self.class.to_s,
  56. o_id: id,
  57. )
  58. end
  59. =begin
  60. destroy all tags of an object
  61. model = Model.find(123)
  62. model.tag_destroy
  63. =end
  64. def tag_destroy(current_user_id = nil)
  65. Tag.tag_destroy(
  66. object: self.class.to_s,
  67. o_id: id,
  68. created_by_id: current_user_id,
  69. )
  70. true
  71. end
  72. class_methods do
  73. =begin
  74. Lists references to objects of this type with certain tag.
  75. Returns array containing object IDs.
  76. @param [String] tag name
  77. @example
  78. Model.tag_references('Tag') # [1, 4, ...]
  79. @return [Array<Integer>]
  80. =end
  81. def tag_references(tag)
  82. Tag
  83. .tag_references(tag: tag, object: name)
  84. .pluck(1)
  85. end
  86. =begin
  87. Lists objects of this type with certain tag
  88. @param [String] tag name
  89. @example
  90. Model.tag_objects('tag')
  91. @return [ActiveRecord::Relation]
  92. =end
  93. def tag_objects(tag)
  94. where id: tag_references(tag)
  95. end
  96. end
  97. end