follower.rb 1.13 KB
module Follower
  extend ActiveSupport::Concern

  def follow(profile, circles)
    circles = [circles] unless circles.is_a?(Array)
    circles.each do |new_circle|
      ProfileFollower.create(profile: profile, circle: new_circle)
    end
  end

  def follows?(profile)
    return false if profile.nil?
    profile.followed_by?(self)
  end

  def unfollow(profile)
    ProfileFollower.with_follower(self).with_profile(profile).destroy_all
  end

  def followed_profiles
    Profile.followed_by self
  end

  def update_profile_circles(profile, new_circles)
    profile_circles = ProfileFollower.with_profile(profile).with_follower(self).map(&:circle)
    circles_to_add = new_circles - profile_circles
    circles_to_remove = profile_circles - new_circles
    circles_to_add.each do |new_circle|
      ProfileFollower.create(profile: profile, circle: new_circle)
    end

    ProfileFollower.where('circle_id IN (?) AND profile_id = ?',
                          circles_to_remove.map(&:id), profile.id).destroy_all
  end

  def remove_profile_from_circle(profile, circle)
    ProfileFollower.with_profile(profile).with_circle(circle).destroy_all
  end

end