Module: EasyRedis

Defined in:
lib/easyredis.rb

Overview

main EasyRedis module which holds all classes and helper methods

Defined Under Namespace

Classes: Collection, FieldNotSortable, FieldNotTextSearchable, Model, Sort, UnknownOrderOption

Class Method Summary collapse

Class Method Details

.connect(options = {}) ⇒ Object

connect to a redis server

takes the same options that Redis#new does from the redis gem

Parameters:

  • options (Hash) (defaults to: {})

    a hash of options to feed to Redis.new



69
70
71
# File 'lib/easyredis.rb', line 69

def self.connect(options = {})
  @redis = Redis.new(options)
end

.redisRedis

access the redis object

Returns:

  • (Redis)


60
61
62
# File 'lib/easyredis.rb', line 60

def self.redis
  @redis
end

.score(obj) ⇒ Number

gets a score for a generic object

The score is determined as follows: First, if the object is a string, string_score is used to get its score. Otherwise, we try calling the following methods on the object in turn, returning the first that works: score, to_f, to_i. If none of those work, we simply return the object itself.

Parameters:

  • obj

    the object to retrive a score for

Returns:

  • (Number)

    the object’s score



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/easyredis.rb', line 44

def self.score(obj)
  if obj.is_a? String
    string_score(obj)
  elsif obj.respond_to? "score"
    obj.score
  elsif obj.respond_to? "to_f"
    obj.to_f
  elsif obj.respond_to? "to_i"
    obj.to_i
  else
    obj
  end
end

.string_score(str) ⇒ Number

generate a ‘score’ for a string used for storing it in a sorted set

This method effectively turns a string into a base 27 floating point number, where 0 corresponds to no letter, 1 to A, 2 to B, etc.

Parameters:

  • str (String)

    the string we are computing a score for

Returns:

  • (Number)

    the string’s score



24
25
26
27
28
29
30
31
32
33
# File 'lib/easyredis.rb', line 24

def self.string_score(str)
  str = str.downcase
  mult = 1.0
  scr = 0.0
  str.each_byte do |b|
    mult /= 27
    scr += (b-'a'.ord+1)*mult
  end
  scr
end