Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. require 'active_support/concern'
  2.  
  3. module Relatable
  4. extend ActiveSupport::Concern
  5.  
  6. included do
  7. has_many :active_relationships, class_name: "Relationship",
  8. #foreign_key: "follower_id",
  9. as: :source,
  10. dependent: :destroy
  11. has_many :passive_relationships, class_name: "Relationship",
  12. #foreign_key: "followed_id",
  13. as: :destination,
  14. dependent: :destroy
  15.  
  16. #has_many :followers, through: :passive_relationships, source: :source, source_type: User
  17.  
  18. end
  19.  
  20. class_methods do
  21.  
  22. end
  23.  
  24.  
  25. def relate!(name, destination)
  26. active_relationships.create!(name: name, destination: destination)
  27. end
  28.  
  29.  
  30. def unrelate!(name, destination)
  31. relation = active_relationships.find_by(name: name, destination_id: destination.id)
  32. relation.destroy if relation
  33. end
  34.  
  35.  
  36. def relatives_from(name, klass=nil)
  37. objects = passive_relationships.where(name: name).map{|ar| ar.destination}
  38. objects.reject!{|o| o.class != klass} if klass
  39. objects
  40. end
  41.  
  42. def relatives_to(name, klass=nil)
  43. objects = active_relationships.where(name: name).map{|ar| ar.destination}
  44. objects.reject!{|o| o.class != klass} if klass
  45. objects
  46. end
  47.  
  48. def owner
  49. self.is_a?(User) ? self : self.user
  50. end
  51.  
  52. #FOLLOW
  53.  
  54. def followers(klass=nil)
  55. relatives_from(Relationship::RELATION_FOLLOW)
  56. end
  57.  
  58.  
  59. def followings(klass=nil)
  60. relatives_to(Relationship::RELATION_FOLLOW)
  61. end
  62.  
  63.  
  64. def follow(destination)
  65. relate!(Relationship::RELATION_FOLLOW, destination)
  66. end
  67.  
  68.  
  69. def unfollow(destination)
  70. unrelate!(Relationship::RELATION_FOLLOW, destination)
  71. end
  72.  
  73.  
  74. def is_following?(other_user)
  75. self.followings.index(other_user)
  76. end
  77.  
  78.  
  79. def relate_name
  80. return self.name if self.respond_to? :name
  81. return self.title if self.respond_to? :title
  82. "#{self.class.name} #{self.id}"
  83. end
  84.  
  85.  
  86.  
  87.  
  88. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement