Skip to content

Commit

Permalink
add HandlerSocket reading
Browse files Browse the repository at this point in the history
  • Loading branch information
grosser committed May 14, 2011
1 parent 2497775 commit 098f76d
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions Gemfile
Expand Up @@ -5,6 +5,7 @@ gem 'activerecord'
group :dev do # not development <-> would add unneeded development dependencies in gemspec
gem 'sqlite3'
gem 'mysql2', '~>0.2.0'
gem 'handlersocket'
gem 'rake'
gem 'rspec', '~>2'
gem 'jeweler'
Expand Down
2 changes: 2 additions & 0 deletions Gemfile.lock
Expand Up @@ -15,6 +15,7 @@ GEM
builder (2.1.2)
diff-lcs (1.1.2)
git (1.2.5)
handlersocket (0.0.2)
i18n (0.5.0)
jeweler (1.6.0)
bundler (~> 1.0.0)
Expand All @@ -38,6 +39,7 @@ PLATFORMS

DEPENDENCIES
activerecord
handlersocket
jeweler
mysql2 (~> 0.2.0)
rake
Expand Down
23 changes: 22 additions & 1 deletion lib/key_value.rb
@@ -1,19 +1,30 @@
require 'active_record'

class KeyValue < ActiveRecord::Base
HS_DEFAULT_CONFIG = {:host => '127.0.0.1', :port => '9998'}
HS_INDEX = 31234 # just some high number...
VERSION = File.read( File.join(File.dirname(__FILE__),'..','VERSION') ).strip
validates_presence_of :key

serialize :value

cattr_accessor :handler_socket

# serialize would treat false the same as nil
def value=(x)
x = x.to_yaml unless x.nil?
write_attribute :value, x
end

def self.get(key)
KeyValue.find_by_key(key).try(:value)
if handler_socket
hs_connection.open_index(HS_INDEX, 'key_values_test', 'key_values', 'index_key_values_on_key', 'value')
result = hs_connection.execute_single(HS_INDEX, '=', [key])
return unless result = result[1][0]
YAML.load(result[0])
else
KeyValue.find_by_key(key).try(:value)
end
end

def self.set(key, value)
Expand Down Expand Up @@ -48,4 +59,14 @@ def self.cache(key)
value
end
end

private

def self.hs_connection
@@hs_connection ||= begin
require 'handlersocket'
config = (handler_socket == true ? HS_DEFAULT_CONFIG : handler_socket)
HandlerSocket.new(config)
end
end
end
28 changes: 28 additions & 0 deletions spec/key_value_spec.rb
Expand Up @@ -2,6 +2,7 @@

describe KeyValue do
before do
KeyValue.handler_socket = false
KeyValue.delete_all
end

Expand Down Expand Up @@ -99,4 +100,31 @@
KeyValue.cache('xxx'){true}.should == false
end
end

if ENV['DB'] == 'mysql'
describe 'with handlersocket' do
before do
KeyValue.handler_socket = true
KeyValue.delete_all
end

it "can get" do
KeyValue['xxx'] = '123'
KeyValue.should_not_receive(:find_by_key)
KeyValue['xxx'].should == '123'
end

it "can get nil" do
KeyValue['xxx'].should == nil
end

it "can get false" do
KeyValue['xxx'] = false
KeyValue.should_not_receive(:find_by_key)
KeyValue['xxx'].should == false
end
end
else
puts 'not running HandlerSocket specs'
end
end

0 comments on commit 098f76d

Please sign in to comment.