Module: ActsAsLikeable::Likeable
- Defined in:
- lib/acts_as_likeable/likeable.rb
Class Method Summary collapse
Instance Method Summary collapse
- #default_conditions ⇒ Object
- #find_likes(extra_conditions = {}) ⇒ Object
- #like(args = {}) ⇒ Object
- #liked_by(liker) ⇒ Object
- #liked_by?(liker) ⇒ Boolean
- #unlike(args = {}) ⇒ Object
- #unliked_by(liker) ⇒ Object
- #update_likes_counter ⇒ Object
Class Method Details
.included(base) ⇒ Object
4 5 6 7 8 9 10 11 12 13 |
# File 'lib/acts_as_likeable/likeable.rb', line 4 def self.included base base.class_eval do belongs_to :likeable, :polymorphic => true has_many :likes, :as => :likeable, :dependent => :delete_all do def likers includes(:liker).map(&:liker) end end end end |
Instance Method Details
#default_conditions ⇒ Object
15 16 17 18 19 20 |
# File 'lib/acts_as_likeable/likeable.rb', line 15 def default_conditions { :likeable_id => self.id, :likeable_type => self.class.base_class.name.to_s } end |
#find_likes(extra_conditions = {}) ⇒ Object
81 82 83 |
# File 'lib/acts_as_likeable/likeable.rb', line 81 def find_likes extra_conditions = {} self.likes.where(extra_conditions) end |
#like(args = {}) ⇒ Object
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 |
# File 'lib/acts_as_likeable/likeable.rb', line 37 def like args = {} return nil if args[:liker].nil? # find the like _likes_ = find_likes({ :liker_id => args[:liker].id, :liker_type => args[:liker].class.name }) if _likes_.count == 0 _like_ = Like.new( :likeable => self, :liker => args[:liker] ) else _like_ = _likes_.first end if _like_.save update_likes_counter _like_ else nil end end |
#liked_by(liker) ⇒ Object
22 23 24 |
# File 'lib/acts_as_likeable/likeable.rb', line 22 def liked_by liker like :liker => liker end |
#liked_by?(liker) ⇒ Boolean
30 31 32 33 34 |
# File 'lib/acts_as_likeable/likeable.rb', line 30 def liked_by? liker return false if liker.nil? _likes_ = find_likes :liker_id => liker.id, :liker_type => liker.class.name _likes_.count > 0 end |
#unlike(args = {}) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/acts_as_likeable/likeable.rb', line 63 def unlike args = {} return false if args[:liker].nil? _likes_ = find_likes({ :liker_id => args[:liker].id, :liker_type => args[:liker].class.name }) return true if _likes_.count == 0 _likes_.each(&:destroy) update_likes_counter true end |
#unliked_by(liker) ⇒ Object
26 27 28 |
# File 'lib/acts_as_likeable/likeable.rb', line 26 def unliked_by liker self.unlike :liker => liker end |
#update_likes_counter ⇒ Object
75 76 77 78 79 |
# File 'lib/acts_as_likeable/likeable.rb', line 75 def update_likes_counter if self.respond_to?(:cached_likes_total=) self.class.where(:id => self.id).update_all(:cached_likes_total => self.likes.count) end end |