initial commit
[acts_as_subscribeable.git] / lib / acts_as_subscribeable.rb
blob54d0d579f8fee82751408f2e625da5037003f1db
1 # ActsAsSubscribeable
2 module RailsJitsu
3   module Acts #:nodoc:
4     module Subscribeable #:nodoc:
6       def self.included(base)
7         base.extend ClassMethods  
8       end
10       module ClassMethods
11         def acts_as_subscribeable
12           has_many :subscriptions, :as => :subscribeable
13           include RailsJitsu::Acts::Subscribeable::InstanceMethods
14           extend RailsJitsu::Acts::Subscribeable::SingletonMethods
15         end
16       end
17       
18       # This module contains class methods
19       module SingletonMethods
20         # Helper method to lookup for subscriptions for a given object.
21         # This method is equivalent to obj.subscription
22         def find_subscriptions_for(obj)
23           # subscribeable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
24           obj_class = obj.class.to_s
25          
26           Subscription.find(:all,
27             :conditions => ["subscribeable_id = ? and subscribeable_type = ?", obj.id, obj_class],
28             :order => "created_at DESC"
29           )
30         end
31         
32         def user_subscribed?(obj, user)
33           obj_class = obj.class.to_s
34          
35           Subscription.find(:first,
36             :conditions => ["user_id = ? and subscribeable_id = ? and subscribeable_type = ?", user.id, obj.id, obj_class],
37             :order => "created_at DESC"
38           )
39         end
40                 
41         def add_subscription(obj, user)
42           obj_class = obj.class.to_s
43           
44           Subscription.create(:user_id => user.id, :subscribeable_id => obj.id, :subscribeable_type => obj_class,
45                               :created_at => Time.now, :updated_at => Time.now) unless user_subscribed?(obj, user)      
46         end
47       
48         def remove_subscription(obj, user)
49           obj_class = obj.class.to_s
50           
51           Subscription.delete_all(
52             ["user_id = ? and subscribeable_id = ? and subscribeable_type = ?", user.id, obj.id, obj_class]
53           )
54         end
55       end
56       
57       # This module contains instance methods
58       module InstanceMethods
59       end
60     end
61   end
62 end