acts_as_follower.rb
2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module ActiveRecord
module Acts
module Follower
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_follower
has_many :follows, :as => :follower, :dependent => :nullify # If a following entity is deleted, keep the follows.
include ActiveRecord::Acts::Follower::InstanceMethods
extend ActiveRecord::Acts::Follower::SingletonMethods
end
end
# This module contains class methods
module SingletonMethods
end
# This module contains instance methods
module InstanceMethods
def following?(followable)
0 < Follow.count(:all, :conditions => [
"follower_id = ? AND follower_type = ? AND followable_id = ? AND followable_type = ?",
self.id, self.class.name, followable.id, followable.class.name
])
end
def follow_count
Follow.count(:all, :conditions => ["follower_id = ? AND follower_type = ?", self.id, self.class.name])
end
def follow(followable)
follow = get_follow(followable)
unless follow
Follow.create(:followable => followable, :follower => self)
end
end
def stop_following(followable)
follow = get_follow(followable)
if follow
follow.destroy
end
end
def follows_by_type(followable_type)
Follow.find(:all, :conditions => ["follower_id = ? AND follower_type = ? AND followable_type = ?", self.id, self.class.name, followable_type])
end
def all_follows
Follow.find(:all, :conditions => ["follower_id = ? AND follower_type = ?", self.id, self.class.name])
end
private
def get_follow(followable)
Follow.find(:first, :conditions => ["follower_id = ? AND follower_type = ? AND followable_id = ? AND followable_type = ?", self.id, self.class.name, followable.id, followable.class.name])
end
end
end
end
end