lib/redis/list.rb in redis-objects-0.3.2 vs lib/redis/list.rb in redis-objects-0.4.0
- old
+ new
@@ -1,24 +1,21 @@
+require File.dirname(__FILE__) + '/base_object'
+
class Redis
#
- # Class representing a Redis list. Instances of Redis::List are designed to
+ # Class representing a Redis list. Instances of Redis::List are designed to
# behave as much like Ruby arrays as possible.
#
- class List
+ class List < BaseObject
require 'enumerator'
include Enumerable
require 'redis/helpers/core_commands'
include Redis::Helpers::CoreCommands
require 'redis/helpers/serialize'
include Redis::Helpers::Serialize
attr_reader :key, :options, :redis
- def initialize(key, *args)
- @key = key
- @options = args.last.is_a?(Hash) ? args.pop : {}
- @redis = args.first || $redis
- end
# Works like push. Can chain together: list << 'a' << 'b'
def <<(value)
push(value)
self # for << 'a' << 'b'
@@ -46,25 +43,31 @@
from_redis redis.lpop(key)
end
# Return all values in the list. Redis: LRANGE(0,-1)
def values
- from_redis range(0, -1)
+ v = from_redis range(0, -1)
+ v.nil? ? [] : v
end
alias_method :get, :values
# Same functionality as Ruby arrays. If a single number is given, return
# just the element at that index using Redis: LINDEX. Otherwise, return
# a range of values using Redis: LRANGE.
def [](index, length=nil)
if index.is_a? Range
range(index.first, index.last)
elsif length
- range(index, length)
+ case length <=> 0
+ when 1 then range(index, index + length - 1)
+ when 0 then []
+ when -1 then nil # Ruby does this (a bit weird)
+ end
else
at(index)
end
end
+ alias_method :slice, :[]
# Delete the element(s) from the list that match name. If count is specified,
# only the first-N (if positive) or last-N (if negative) will be removed.
# Use .del to completely delete the entire key.
# Redis: LREM