From f73d1ef2149c06135f99e0ec18457c5aa9dd85a1 Mon Sep 17 00:00:00 2001 From: Sung Won Cho Date: Sun, 6 Mar 2016 09:15:00 +1100 Subject: [PATCH] Fix friends_with to return only true when friendship is accepted. Fix #21 --- lib/has_friendship/friendable.rb | 2 +- lib/has_friendship/friendship.rb | 14 ++++++++++---- spec/has_friendship/friendable_spec.rb | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/has_friendship/friendable.rb b/lib/has_friendship/friendable.rb index 49834fe..c397658 100644 --- a/lib/has_friendship/friendable.rb +++ b/lib/has_friendship/friendable.rb @@ -85,7 +85,7 @@ def on_relation_with(friend) end def friends_with?(friend) - HasFriendship::Friendship.find_relation(self, friend).any? + HasFriendship::Friendship.find_relation(self, friend, status: 'accepted').any? end private diff --git a/lib/has_friendship/friendship.rb b/lib/has_friendship/friendship.rb index 4e003cd..676def8 100644 --- a/lib/has_friendship/friendship.rb +++ b/lib/has_friendship/friendship.rb @@ -1,11 +1,17 @@ module HasFriendship class Friendship < ActiveRecord::Base - def self.relation_attributes(one, other) - { + def self.relation_attributes(one, other, status: nil) + attr = { friendable_id: one.id, friendable_type: one.class.base_class.name, friend_id: other.id } + + if status + attr[:status] = status + end + + attr end def self.create_relation(one, other, options) @@ -14,8 +20,8 @@ def self.create_relation(one, other, options) relation.save end - def self.find_relation(friendable, friend) - where relation_attributes(friendable, friend) + def self.find_relation(friendable, friend, status: nil) + where relation_attributes(friendable, friend, status: status) end def self.exist?(friendable, friend) diff --git a/spec/has_friendship/friendable_spec.rb b/spec/has_friendship/friendable_spec.rb index 6b4b49c..fbd00e7 100644 --- a/spec/has_friendship/friendable_spec.rb +++ b/spec/has_friendship/friendable_spec.rb @@ -249,6 +249,20 @@ expect(jon.friends_with?(user)).to eq false end end + + context 'when a pending friendship exists' do + it 'returns false' do + create_friendship(user, friend, status: 'pending') + expect(user.friends_with?(friend)).to eq false + end + end + + context 'when a blocked friendship exists' do + it 'returns false' do + create_friendship(user, friend, status: 'blocked') + expect(user.friends_with?(friend)).to eq false + end + end end end end