appsbakery/mongoid_follow
In Gemfile:
gem 'mongoid_follow', github: "ciihla/mongoid_follow"
"follower" is a model who follows "followee" is a model who would be followed
To make mongoid_follow usable you need to include Mongoid::Followee into your document who would be followed then you also need to include Mongoid::Follower in your follower model:
class User include Mongoid::Document include Mongoid::Followee include Mongoid::Follower end class Group include Mongoid::Document include Mongoid::Followee end
You can then follow a model using:
@bonnie = User.create @clyde = User.create @bonnie.follow!(@clyde) # is the same like @bonnie.follow!(@clyde, "follow") @bonnie.unfollow!(@clyde) # is the same like @bonnie.unfollow!(@clyde, "follow")
You can specify different relations:
@bonnie.follow!(@clyde, "friends") # @bonnie marked @clyde as friend
You can also see whether a model is a follower of another model or if a model is a followee of another model:
@clyde.follows?(@bonnie) # is the same like @clyde.follows?(@bonnie, "follow") @bonnie.followee?(@clyde) # is the same like @bonnie.followee?(@clyde, "follow") @clyde.follows?(@bonnie, "friends") # @clyde marked @bonnie as his friend? @bonnie.followee?(@clyde, "friends")
You can also be a follower of other models
@gang = Group.create @bonnie.follow!(@group) # @bonnie.follow!(@group, "follow") @gang.follower?(@bonnie) @bonnie.follows?(@gang)
Get all followers/followees by
@gang.all_followers # is the same like @gang.all_followers("follow") @bonnie.all_followees # is the same like @bonnie.all_followees("follow")
You can also get followers/followees by a certain model
@gang.all_followers("follow", User) @bonnie.all_followees("follow", Gang)
Get all users that I’m in a relation “friends” with:
current_user.followees.where(followee_type: "User", relation: "friends") # current user acts as follower. Others are followees
You can attach callbacks to the follower/followee models before or after the follow.
# Follower model def before_follow(followee) puts 'Notify me' end # Other follower callbacks after_follow before_unfollow after_unfollow
In User model:
include Mongoid::Followee include Mongoid::Follower def after_follow(model) if model.follows?(self) self.follow!(model, "friends") model.follow!(self, "friends") end end def after_unfollow(model) self.unfollow!(model, "friends") model.unfollow!(self, "friends") end
Note: careful with using callbacks, we have no transaction so if it breaks on your callbacks, what gets saved is saved.
-
Any bug or issue, please send me an email to [email protected]
gem install 'mongoid' gem install 'bson_ext' gem install 'database_cleaner' gem install 'rspec' rake spec/specs/follow_spec_rb
Awesome thanks to:
mongoid_followable Tristan Peralta
Copyright © Alec Guintu. See LICENSE.txt for further details.