require 'rubygems' require 'sinatra' require 'redis' # To use, simply start your Redis server and boot this # example app with: # ruby example_note_keeping_app.rb # # Point your browser to http://localhost:4567 and enjoy! # before do @redis = Redis.new end helpers do def tag_link(t, title = nil) arr = t.is_a?(Array) ? t : (@current_tags || []).dup.push(t) path = arr.uniq.join('/') %!#{title || t}! end end def load_notes(ids) ids.map do |note_id| Marshal.load(@redis["note-#{note_id}"]) end end get '/' do # Load all notes @notes = load_notes(begin @redis.set_members('all-notes') rescue RedisError [] end) erb :index end get '/tags/*' do @current_tags = params[:splat].first.split('/') redirect '/' if @current_tags.empty? # Names of the tag-sets sets = @current_tags.map { |t| "tag-#{t}" } # Load all notes that reside in the intersection of these sets @notes = load_notes @redis.set_intersect(*sets) erb :index end get '/new' do erb :new end post '/new' do # Extract tags from request parameters tags = params[:tags].gsub(/\s+/, '').split(',') # Get ID for the new note note_id = @redis.incr(:note_counter) # Store the note @redis["note-#{note_id}"] = Marshal.dump({ :contents => params[:contents], :tags => tags }) @redis.set_add("all-notes", note_id); # Add the ID to the tag-sets tags.each { |t| @redis.set_add("tag-#{t}", note_id) } redirect '/' end __END__ @@ layout
<%= note[:contents] %>