arunthampi / memento

Simple HTTP Proxy for Memcached

This URL has Read+Write access

memento / memento.ru
100644 40 lines (30 sloc) 1.0 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require 'sinatra/async'
require 'yaml'
 
class Memento < Sinatra::Base
  register Sinatra::Async
 
  attr_reader :host, :port, :memcache
 
  def initialize(opts = {})
    @@memcache = nil
    
    unless File.exists?(opts[:config_file])
      raise StandardError, "You must have a config/memento.yml file"
    else
      config = YAML::load(File.read(opts[:config_file]))
      server = config['server']
      if server.nil? || (@host, @port = server.split(':')).size != 2
        raise StandardError, "You must specify a Memcached server with the following format: host:port"
      end
    end
  end
 
  def memcache
    @@memcache ||= EM::P::Memcache.connect(@host, @port.to_i)
  end
 
  aget '/get/:key' do |key|
    memcache.get(key) { |value| body { value } }
  end
 
  apost '/set/' do
    key, value = params[:key], params[:value]
    expiry = params[:expiry] || '86400'
    
    memcache.set(key, value, expiry) { body { value } }
  end
  
end
 
run Memento.new(:config_file => 'config/memento.yml')