class RedisFile::SortedSetArgumentHandler

Takes in the variable length array of arguments for a zinterstore/zunionstore method and parses them into a few attributes for the method to access.

Handles throwing errors for various scenarios (matches redis):

* Custom weights specified, but not enough or too many given
* Invalid aggregate value given
* Multiple aggregate values given

Attributes

aggregate[R]
Symbol

The aggregate method to use for the output values. One of %w(sum min max) expected

keys[RW]
Array

The actual keys in the argument list

number_of_keys[RW]
Integer

Number of keys in the argument list

type[RW]

Used internally

weights[RW]
Array

integers for weighting the values of each key - one number per key expected

Public Class Methods

new(args) click to toggle source

Expects all the argments for the method to be passed as an array

# File lib/redis-file/sorted_set_argument_handler.rb, line 23
def initialize args
  # Pull out known lengths of data
  self.number_of_keys = args.shift
  self.keys = args.shift(number_of_keys)
  # Handle the variable lengths of data (WEIGHTS/AGGREGATE)
  args.inject(self) {|handler, item| handler.handle(item) }

  # Defaults for unspecified things
  self.weights ||= Array.new(number_of_keys) { 1 }
  self.aggregate ||= :sum

  # Validate values
  raise(Redis::CommandError, "ERR syntax error") unless weights.size == number_of_keys
  raise(Redis::CommandError, "ERR syntax error") unless [:min, :max, :sum].include?(aggregate)
end

Public Instance Methods

aggregate=(str) click to toggle source

Only allows assigning a value once - raises Redis::CommandError if a second is given

# File lib/redis-file/sorted_set_argument_handler.rb, line 40
def aggregate=(str)
  raise(Redis::CommandError, "ERR syntax error") if (defined?(@aggregate) && @aggregate)
  @aggregate = str.to_s.downcase.to_sym
end
handle(item) click to toggle source

Decides how to handle an item, depending on where we are in the arguments

# File lib/redis-file/sorted_set_argument_handler.rb, line 46
def handle(item)
  case item
  when "WEIGHTS"
    self.type = :weights
    self.weights = []
  when "AGGREGATE"
    self.type = :aggregate
  when nil
    # This should never be called, raise a syntax error if we manage to hit it
    raise(Redis::CommandError, "ERR syntax error")
  else
    send "handle_#{type}", item
  end
  self
end
handle_aggregate(item) click to toggle source
# File lib/redis-file/sorted_set_argument_handler.rb, line 66
def handle_aggregate(item)
  self.aggregate = item
end
handle_weights(item) click to toggle source
# File lib/redis-file/sorted_set_argument_handler.rb, line 62
def handle_weights(item)
  self.weights << item
end
inject_block() click to toggle source
# File lib/redis-file/sorted_set_argument_handler.rb, line 70
def inject_block
  lambda { |handler, item| handler.handle(item) }
end