Class: Alloc8::Tor
- Inherits:
-
Object
- Object
- Alloc8::Tor
- Defined in:
- lib/alloc8.rb
Class Method Summary collapse
-
.with_resource(klass, host, port, db = nil) ⇒ Object
block to allocate a resource.
Instance Method Summary collapse
-
#acquire(klass, timeout = 0) ⇒ Object
acquire next available resource.
-
#available(klass) ⇒ Object
list all available items in resource class.
-
#create(klass, resource) ⇒ Object
create a resource in a class.
-
#initialize(host, port, db = nil) ⇒ Tor
constructor
initialize connection to redis.
-
#list(klass) ⇒ Object
list all resources in class.
-
#purge(klass) ⇒ Object
delete a resource class.
-
#reset(klass) ⇒ Object
reset available items in resource class.
-
#return(klass, resource) ⇒ Object
return resource.
Constructor Details
#initialize(host, port, db = nil) ⇒ Tor
initialize connection to redis
6 7 8 9 |
# File 'lib/alloc8.rb', line 6 def initialize(host, port, db=nil) @redis = Redis.new(:host => host, :port => port) @redis.select(db) if db end |
Class Method Details
.with_resource(klass, host, port, db = nil) ⇒ Object
block to allocate a resource
61 62 63 64 65 66 67 68 69 |
# File 'lib/alloc8.rb', line 61 def self.with_resource(klass, host, port, db=nil) a = Alloc8::Tor.new host, port, db begin res = a.acquire(klass) yield res ensure a.return(klass, res) end end |
Instance Method Details
#acquire(klass, timeout = 0) ⇒ Object
acquire next available resource
49 50 51 52 |
# File 'lib/alloc8.rb', line 49 def acquire(klass, timeout = 0) akey, res = @redis.brpop key(klass, :avail), timeout res end |
#available(klass) ⇒ Object
list all available items in resource class
39 40 41 42 43 44 45 46 |
# File 'lib/alloc8.rb', line 39 def available(klass) akey = key(klass, :avail) avail = [] @redis.llen(akey).times do |i| avail << @redis.lindex(akey, i) end avail end |
#create(klass, resource) ⇒ Object
create a resource in a class
12 13 14 15 16 |
# File 'lib/alloc8.rb', line 12 def create(klass, resource) if @redis.sadd(key(klass), resource.to_s) @redis.lpush key(klass, :avail), resource.to_s end end |
#list(klass) ⇒ Object
list all resources in class
19 20 21 |
# File 'lib/alloc8.rb', line 19 def list(klass) @redis.smembers(key(klass)) end |
#purge(klass) ⇒ Object
delete a resource class
24 25 26 27 |
# File 'lib/alloc8.rb', line 24 def purge(klass) nkeys = @redis.del key(klass, :avail), key(klass) nkeys == 2 # true if purged all end |
#reset(klass) ⇒ Object
reset available items in resource class
30 31 32 33 34 35 36 |
# File 'lib/alloc8.rb', line 30 def reset(klass) akey = key(klass, :avail) @redis.del akey @redis.smembers(key(klass)).each do |resource| @redis.lpush akey, resource.to_s end end |
#return(klass, resource) ⇒ Object
return resource
55 56 57 58 |
# File 'lib/alloc8.rb', line 55 def return(klass, resource) raise Exception.new("Invalid resource #{resource} for class #{klass}") if !@redis.sismember key(klass), resource.to_s @redis.lpush key(klass, :avail), resource.to_s end |