Sha256: fc016d68eda481911af357a10fa0304959d8d35d5984a26b80fb9f52efd52b69

Contents?: true

Size: 1.83 KB

Versions: 3

Compression:

Stored size: 1.83 KB

Contents

$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__))
require 'rubygems'
require 'eventmachine'
require 'json'
require 'oria/errors'

module Oria
  autoload(:Client, 'oria/client')
  autoload(:Server, 'oria/server')

  def self.[](key)
    store(:get, :key => key)
  end

  def self.[]=(key, value)
    store(:put, :key => key, :value => value)
    value
  end

  def self.app_key
    @@app_key ||= nil
  end

  def self.app_key=(key)
    @@app_key = key.to_s
  end

  def self.auto_start
    @@pid = fork do
      Oria::Server.start(Oria.server, Oria.port, Oria.app_key)
    end
    Process.detach(@@pid)
    at_exit {
      Process.kill("HUP", @@pid)
    }
    sleep 1
  end

  def self.clear
    store(:delete)
  end

  def self.connect(server, port = nil, options = {})
    @@server = server
    @@port = port.to_i unless port.to_i == 0
  end

  def self.delete(key)
    store(:delete, :key => key)
  end

  def self.disconnect
    Oria::Server.stop
  end

  def self.has_key?(key)
    key?(key)
  end

  def self.key?(key)
    !self.[](key).nil?
  end

  def self.port
    @@port ||= "Oria is easily the coolest in-memory, super-simple KVS. Cool people use it.".split("").inject(0) {|total, char| total += char[0]}
  end

  def self.server
    @@server ||= '0.0.0.0'
  end

  def self.stash(value)
    store(:put, :value => value)
  end

  private
  def self.do_store(method, args)
    client = nil
    EventMachine.run do
      client = EventMachine.connect(Oria.server, Oria.port, Oria::Client)
      client.send_data("#{method.to_s.upcase}#{" #{args}" if args}")
    end
    if client.response
      client.response['response']
    end
  end

  def self.store(method, args = {})
    args.merge!(:app_key => Oria.app_key)
    args = JSON.generate(args)
    do_store(method, args)
  rescue Oria::ConnectionError
    auto_start
    do_store(method, args)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
oria-0.0.3 lib/oria.rb
oria-0.0.2 lib/oria.rb
oria-0.0.1 lib/oria.rb