Skip to content

Instantly share code, notes, and snippets.

@delba
Last active December 17, 2015 01:29
Show Gist options
  • Select an option

  • Save delba/5528277 to your computer and use it in GitHub Desktop.

Select an option

Save delba/5528277 to your computer and use it in GitHub Desktop.
Starring items with redis
class Item < ActiveRecord::Base
def stars
User.find star_ids
end
def stars_count
$redis.scard redis_key(:stars)
end
private
def star_ids
$redis.smembers redis_key(:stars)
end
def redis_key(column)
"#{self.class.table_name}:#{id}:#{column}"
end
end
class ItemsController < ApplicationController
before_action :authenticate, :set_item
def show
@item = Item.find(params[:id])
end
def star
current_user.star! @item
end
def unstar
current_user.unstar! @item
end
private
def authenticate
redirect_to signin_url unless signed_in?
end
def set_item
@item = Item.find(params[:id])
end
end
$redis = Redis.new(host: 'localhost', port: 6379)
MyApp::Application.routes.draw do
resources :items do
member do
post 'star'
delete 'unstar'
end
end
end
<article>
<% if signed_in? %>
<% if current_user.star? @item %>
<%= buttton_to 'Unstar', unstar_item_path(@item), method: :delete %>
<% else %>
<%= buttton_to 'Star', star_item_path(@item) %>
<% end %>
<% end %>
<h1><%= @item.name %></h1>
<%= simple_format @item.description %>
</article>
class User < ActiveRecord::Base
def star!(item)
$redis.multi do
$redis.sadd(redis_key(:stars), item.id)
$redis.sadd(item.redis_key(:stars), id)
end
end
def unstar!(item)
$redis.multi do
$redis.srem(redis_key(:stars), item.id)
$redis.srem(item.redis_key(:stars), id)
end
end
def stars
Item.find star_ids
end
def star?(item)
$redis.sismember(redis_key(:stars), item.id)
end
def stars_count
$redis.scard redis_key(:stars)
end
private
def star_ids
$redis.smembers redis_key(:stars)
end
def redis_key(column)
"#{self.class.table_name}:#{id}:#{column}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment