Skip to content

Instantly share code, notes, and snippets.

@xeviknal
Last active August 10, 2021 19:59
Show Gist options
  • Save xeviknal/d242648bbff3d06aad08 to your computer and use it in GitHub Desktop.
Save xeviknal/d242648bbff3d06aad08 to your computer and use it in GitHub Desktop.
Socialize Models with Redis and Rails
# 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
# 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
# app/models/concern/socialize.rb
# This concern enables the socialization of one model via `socialize_for` class method.
# Every time a new instance is created it updates a redis set in the association with its belonging user.
require 'active_support/concern'
module Socialize
module Socializer
extend ActiveSupport::Concern
included do
after_create :__update_socialized_models
end
def __update_socialized_models
self.class.model_updates.each do |association, set_name|
self.send(association).send(set_name) << self.user.id
end
end
module ClassMethods
def model_updates
@model_updates ||= []
end
def socialize_for(association, set_name)
model_updates << [ association, set_name ]
end
end
end
end
# 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