Skip to content

Instantly share code, notes, and snippets.

@CaDs
Last active October 18, 2018 05:54
Show Gist options
  • Save CaDs/c11b3a0961b8db1602a0d818c7342cb1 to your computer and use it in GitHub Desktop.
Save CaDs/c11b3a0961b8db1602a0d818c7342cb1 to your computer and use it in GitHub Desktop.
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_many :connections, dependent: :destroy
has_many :follower_connections, foreign_key: :following_id, class_name: 'Connection'
has_many :followers, through: :follower_connections, source: :follower
has_many :following_connections, foreign_key: :follower_id, class_name: 'Connection'
has_many :following, through: :following_connections, source: :following
has_many :following_posts, through: :following, source: :post
def fetch_feed
cache_keys = redis.zrevrange(cache_key, 0, -1)
.map { |id| Post.cache_key_for(id: id) }
return [] unless cache_keys.any?
Rails.cache.fetch_multi(*cache_keys, expires: 1.minute, race_condition_ttl: 5.seconds) do |key|
id = Post.id_from_cache_key(key: key)
Post.find_by(id: id)
end.values
end
def fetch_read_feed
Post.eager_load(:user)
.where(user: self.following + [self])
.order('posts.created_at DESC')
end
def add_to_cache(post:)
redis.zadd(cache_key, post.created_at.to_i, post.id)
end
end
user = User.first
# => User Load (0.3ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
user.followers
# => SELECT `users`.* FROM `users` INNER JOIN `connections` ON `users`.`id` = `connections`.`follower_id` WHERE `connections`.`following_id` = 4
user.following
# => SELECT `users`.* FROM `users` INNER JOIN `connections` ON `users`.`id` = `connections`.`following_id` WHERE `connections`.`follower_id` = 4
user.fetch_feed
# => User Load (0.4ms) SELECT `users`.* FROM `users` INNER JOIN `connections` ON `users`.`id` = `connections`.`following_id` WHERE `connections`.`follower_id` = 4
# => SQL (0.7ms) SELECT ..... FROM `posts` LEFT OUTER JOIN `users` ON `users`.`id` = `posts`.`user_id` WHERE `posts`.`user_id` IN (5, 4) ORDER BY posts.created_at DESC LIMIT 11
user.fetch_feed
# => Post Load (5.9ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 21 LIMIT 1
# => Post Load (0.7ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 20 LIMIT 1
# => Post Load (0.6ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 19 LIMIT 1
# => Post Load (0.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 18 LIMIT 1
# => Post Load (0.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 17 LIMIT 1
# => Post Load (0.5ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 16 LIMIT 1
# => Post Load (0.4ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 15 LIMIT 1
# => Post Load (0.3ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 14 LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment