Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'active_support/concern'
- module Relatable
- extend ActiveSupport::Concern
- included do
- has_many :active_relationships, class_name: "Relationship",
- #foreign_key: "follower_id",
- as: :source,
- dependent: :destroy
- has_many :passive_relationships, class_name: "Relationship",
- #foreign_key: "followed_id",
- as: :destination,
- dependent: :destroy
- #has_many :followers, through: :passive_relationships, source: :source, source_type: User
- end
- class_methods do
- end
- def relate!(name, destination)
- active_relationships.create!(name: name, destination: destination)
- end
- def unrelate!(name, destination)
- relation = active_relationships.find_by(name: name, destination_id: destination.id)
- relation.destroy if relation
- end
- def relatives_from(name, klass=nil)
- objects = passive_relationships.where(name: name).map{|ar| ar.destination}
- objects.reject!{|o| o.class != klass} if klass
- objects
- end
- def relatives_to(name, klass=nil)
- objects = active_relationships.where(name: name).map{|ar| ar.destination}
- objects.reject!{|o| o.class != klass} if klass
- objects
- end
- def owner
- self.is_a?(User) ? self : self.user
- end
- #FOLLOW
- def followers(klass=nil)
- relatives_from(Relationship::RELATION_FOLLOW)
- end
- def followings(klass=nil)
- relatives_to(Relationship::RELATION_FOLLOW)
- end
- def follow(destination)
- relate!(Relationship::RELATION_FOLLOW, destination)
- end
- def unfollow(destination)
- unrelate!(Relationship::RELATION_FOLLOW, destination)
- end
- def is_following?(other_user)
- self.followings.index(other_user)
- end
- def relate_name
- return self.name if self.respond_to? :name
- return self.title if self.respond_to? :title
- "#{self.class.name} #{self.id}"
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement