Lightning-Quick Redis Viewer

I've had the opportunity to work with the Redis datastore this week. If you're not familiar with it, Redis is a blindingly-fast, in-memory key-value store. It supports several nice features such as string, list and set support (complete with set operations) and the ability to persist data to disk. Check out the official site for lots more info.

My project revolved around data collection, and I pretty quickly ran into the need to see what I was actually shoving into the database. After 10 minutes and only ~50 lines, I came up with a Sinatra backed Redis viewer. See the code below, or check out my gist on Github!

# app.rb
require 'rubygems'
require 'haml'
require 'sinatra'
require 'redis'

helpers do
  def redis
    @redis ||= Redis.new
  end
end

get "/" do
  @keys = redis.keys("*")
  haml :index
end

get "/:key" do
  @key = params[:key]
  @data = case redis.type(@key)
  when "string"
    Array(redis[@key])
  when "list"
    redis.lrange(@key, 0, -1)
  when "set"
    redis.set_members(@key)
  else
    []
  end
  haml :show
end

# views/index.haml
%html
%body
  %h1 Current Keys
  %ul
    - @keys.each do |key|
      %li
        %a{:href => "/#{key}"}= key

# views/show.haml
%html
%body
  %h1= "Data stored in '#{@key}'"
  %ul
    -@data.each do |data|
      %li
        %p= data
blog comments powered by Disqus