Last active
August 10, 2021 19:59
-
-
Save xeviknal/d242648bbff3d06aad08 to your computer and use it in GitHub Desktop.
Socialize Models with Redis and Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/event.rb | |
# Event model has a set (event_users_ids) tracking all the users that has an inscription to it. | |
# The set update is made in the inscription model which models the relation between the event and its participants. | |
# The operation to get the friends participating in one event is done via redis set operations (&) | |
class Event < ActiveRecord::Base | |
include Redis::Objects | |
has_many :inscriptions | |
set :event_users_ids | |
def friends_for(user) | |
return [] unless user.present? | |
self.event_users_ids & user.followed_user_ids # operation performed in Redis | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/inscription.rb | |
# The event set is updated every time a new Inscription instance is created. | |
class Inscription < ActiveRecord::Base | |
include Socialize::Socializer | |
belongs_to :event | |
belongs_to :user | |
socialize_for :event, :event_users_ids | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
# user has a set with all the other users following her/him | |
class User < ActiveRecord::Base | |
include Redis::Objects | |
set :followed_user_ids | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment