lib/ohm.rb in ohm-0.0.14 vs lib/ohm.rb in ohm-0.0.15
- old
+ new
@@ -4,11 +4,11 @@
module Ohm
# Provides access to the Redis database. This is shared accross all models and instances.
def redis
- Thread.current[:redis]
+ Thread.current[:redis] ||= Ohm::Redis.new(*options)
end
def redis=(connection)
Thread.current[:redis] = connection
end
@@ -21,24 +21,29 @@
# @option options [#to_s] :db (0) Database number.
# @option options [#to_s] :timeout (0) Database timeout in seconds.
# @example Connect to a database in port 6380.
# Ohm.connect(:port => 6380)
def connect(*options)
- self.redis = Ohm::Redis.new(*options)
+ self.redis = nil
+ @options = options
end
+ def options
+ @options
+ end
+
# Clear the database.
def flush
redis.flushdb
end
# Join the parameters with ":" to create a key.
def key(*args)
args.join(":")
end
- module_function :key, :connect, :flush, :redis, :redis=
+ module_function :key, :connect, :flush, :redis, :redis=, :options
module Attributes
class Collection
include Enumerable
@@ -95,10 +100,15 @@
def ==(other)
to_ary == other
end
+ # @return [true, false] Returns whether or not the collection is empty.
+ def empty?
+ size.zero?
+ end
+
private
def instantiate(raw)
model ? raw.collect { |id| model[id] } : raw
end
@@ -117,22 +127,39 @@
# event.participants << "Albert"
# event.participants << "Benoit"
# event.participants.all #=> ["Albert", "Benoit"]
class List < Collection
- # @param value [#to_s] Pushes value to the list.
+ # @param value [#to_s] Pushes value to the tail of the list.
def << value
db.rpush(key, value)
end
- def empty?
- db.llen(key).zero?
+ # @return [String] Return and remove the last element of the list.
+ def pop
+ db.rpop(key)
end
+ # @return [String] Return and remove the first element of the list.
+ def shift
+ db.lpop(key)
+ end
+
+ # @param value [#to_s] Pushes value to the head of the list.
+ def unshift(value)
+ db.lpush(key, value)
+ end
+
+ # @return [Array] Elements of the list.
def raw
db.list(key)
end
+
+ # @return [Integer] Returns the number of elements in the list.
+ def size
+ db.llen(key)
+ end
end
# Represents a Redis set.
#
# @example Use a set attribute.
@@ -163,19 +190,20 @@
def delete(value)
db.srem(key, value)
end
- def empty?
- db.scard(key).zero?
- end
-
def include?(value)
db.sismember(key, value)
end
def raw
db.smembers(key)
+ end
+
+ # @return [Integer] Returns the number of elements in the set.
+ def size
+ db.scard(key)
end
end
end
class Model