Skip to content

Commit

Permalink
Define state machine for Friendship. Change the update calls for the …
Browse files Browse the repository at this point in the history
…state methods
  • Loading branch information
ArmandoMendoza committed Apr 14, 2016
1 parent fde89eb commit ba25ba2
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
6 changes: 2 additions & 4 deletions lib/has_friendship/friendable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ def friend_request(friend)

def accept_request(friend)
on_relation_with(friend) do |one, other|
HasFriendship::Friendship.find_unblocked_friendship(one, other)
.update(status: 2)
HasFriendship::Friendship.find_unblocked_friendship(one, other).accept!
end
end

Expand All @@ -66,8 +65,7 @@ def decline_request(friend)

def block_friend(friend)
on_relation_with(friend) do |one, other|
HasFriendship::Friendship.find_unblocked_friendship(one, other)
.update(status: 3, blocker_id: self.id)
HasFriendship::Friendship.find_unblocked_friendship(one, other).block!
end
end

Expand Down
15 changes: 15 additions & 0 deletions lib/has_friendship/friendship.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
module HasFriendship
class Friendship < ActiveRecord::Base

enum status: { pending: 0, requested: 1, accepted: 2, blocked: 3 } do
event :accept do
transition [:pending, :requested] => :accepted
end

event :block do
before do
self.blocker_id = self.friendable.id
end

transition all - [:blocked] => :blocked
end
end

def self.relation_attributes(one, other, status: nil)
attr = {
friendable_id: one.id,
Expand Down
1 change: 1 addition & 0 deletions spec/rails_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

require 'shoulda'
require 'support/friendship_macro'
require 'stateful_enum'

load 'internal/db/schema.rb'

Expand Down

0 comments on commit ba25ba2

Please sign in to comment.