ruby 61 lines · 2 tabs

Rails Kredis for higher-level Redis operations

Maya Patel Jan 2026
2 tabs
class Post < ApplicationRecord
  # View counter - increments without hitting the database
  kredis_counter :view_count, expires_in: 1.day

  # Recent viewers list - stores last 10 viewer IDs
  kredis_unique_list :recent_viewers, limit: 10

  # Flag for featured status
  kredis_flag :featured

  # Hash for cached statistics
  kredis_hash :statistics

  def increment_views!(user_id)
    view_count.increment
    recent_viewers.prepend(user_id)

    # Update database counter periodically
    if view_count.value % 10 == 0
      update_column(:views, views + 10)
    end
  end

  def viewer_count
    recent_viewers.elements.size
  end

  def stats
    statistics.entries.presence || compute_and_cache_stats
  end

  private

  def compute_and_cache_stats
    stats = {
      'likes' => likes.count,
      'comments' => comments.count,
      'shares' => shares.count
    }
    statistics.update(stats)
    stats
  end
end
2 files · ruby Explain with highlit

Kredis provides typed Redis structures as Active Model attributes, simplifying common patterns like counters, flags, and lists. Instead of raw Redis commands, I define kredis accessors on models that handle serialization automatically. Counters track metrics like view counts, lists manage ordered collections, and flags store boolean states. Kredis uses connection pooling and handles expiration seamlessly. For real-time features, I combine Kredis with Action Cable—store online users in a Redis set, broadcast presence updates. The library integrates with Rails' encrypted credentials for sensitive data. This abstraction makes Redis feel like native Rails, improving developer productivity while maintaining performance.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Rails Kredis for higher-level Redis operations — share card
Link copied