Class: Session::SessionClient

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_session.rb

Overview

Example:

require 'redis_session'
session = Session::SessionClient.new(:prefix => 'example', :host => '10.0.0.31')

session.save('key', 'value') # save key with the value of value without expire, return true if successful
puts session.restore('key')  # will return "value"

session.save('self_destruct', 'in', 10) # save the key self_destruct with the value of 'in', and will terminates in 10 seconds
sleep 10.1
session.restore('self_destruct')      # returns empty hash
session.restore('self_destruct', nil) # returns default value of nil

session.save('boom', { :bomb => 'ball' }, 10) # saving a ruby object
puts session.ttl('boom') # should return the seconds left to the key to live or -1

session.expire('key', 60)   # the key will be gone in 60 seconds
puts session.restore('key') # prints 'value'

puts 'has value' if session.value? 'key' # check if key has a value

session.delete('key')       # deleted it before time :)
                            # it's alias to remove

puts 'still here' if session.key? 'key' # do we have the key ?

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SessionClient

Creates an object of SessionClient

Parameters

:host

the ip address or host name of the redis server default localhost

:path

the path to unix socket of redis (instead of :host)

:port

the port number for the host - default 6379

:db

the Redis database number - default 0

:prefix

a prefix string for storing and retriving information

:expire

global expiry of keys in seconds

Raises:

  • (ArgumentError)


77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/redis_session.rb', line 77

def initialize(options={})
  raise ArgumentError, 'options must be Hash' unless options.kind_of? Hash

  options[:host]   ||= 'localhost' unless options[:path]
  options[:port]   ||= 6379
  options[:db]     ||= 0
  options[:prefix] ||= ''
  options[:expire] ||= 0

  @options = options
  @redis   = Redis.new(@options)
end

Instance Method Details

#expire(key, ttl) ⇒ Object

Set an expire time in seconds to a key. If the key already has an expire time, it reset it to a new time.

key

The name of the key to set the expire time

ttl

The time in seconds to expire the key

returns

true if successful or false if not



171
172
173
174
175
176
177
178
# File 'lib/redis_session.rb', line 171

def expire(key, ttl)
  a_key = make_key(key)
  @redis.expire(a_key, ttl)
rescue Redis::BaseConnectionError
  raise
rescue Exception
  false
end

#key?(key) ⇒ Boolean

Check to see if a key exists

key

The name of the key to check

returns

true if it exists or false otherwise

Returns:

  • (Boolean)


227
228
229
230
231
232
233
234
235
# File 'lib/redis_session.rb', line 227

def key?(key)
  a_key = make_key(key)
  @redis.exists a_key

rescue Redis::BaseConnectionError
  raise
rescue Exception
  false
end

#prefixObject

Getting the prefix name

returns

The prefix string



97
98
99
# File 'lib/redis_session.rb', line 97

def prefix
  @options[:prefix]
end

#prefix=(prefix) ⇒ Object

Changing the prefix string _(will not effect existing keys)_

prefix

The new prefix to be set



108
109
110
# File 'lib/redis_session.rb', line 108

def prefix=(prefix)
  @options[:prefix] = prefix
end

#remove(key) ⇒ Object Also known as: delete

Deleting a key from the session

key

The name of the key to be removed

returns

true if successful or false otherwise



208
209
210
211
212
213
214
215
216
# File 'lib/redis_session.rb', line 208

def remove(key)
  a_key = make_key(key)
  @redis.del(a_key)

rescue Redis::BaseConnectionError
  raise
rescue Exception
  false
end

#restore(key, default = {}) ⇒ Object

Restoring a key’s value or providing a default value instead

key

The name of the key to restore

default

The value to provide if no value was given. Default empty Hash

returns

The value of the key or default value



151
152
153
154
155
156
157
158
159
# File 'lib/redis_session.rb', line 151

def restore(key, default={})
  a_key = make_key(key)
  data  = @redis.get(a_key)
  data.nil? ? default : Marshal.load(data)
rescue Redis::BaseConnectionError
  raise
rescue Exception
  default
end

#save(key, value, ttl = nil) ⇒ Object

Saving a key with a value

key

the name of the key to be saved

value

the value to save. Can be any Ruby object

ttl

expiry time to the key. Default nil.

returns

true if successful or false otherwise

Note

If expire was set and ttl is nil, then the key will have expire by the :expire option



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/redis_session.rb', line 125

def save(key, value, ttl = nil)
  a_key  = make_key(key)
  a_data = Marshal.dump(value)
  ttl ||= @options[:expire]
  if ttl > 0
    @redis.setex(a_key, ttl, a_data)
  else
    @redis.set(a_key, a_data)
  end
  true
rescue Redis::BaseConnectionError
  raise
rescue Exception
  false
end

#scan_by(&block) ⇒ Object

scan for partial value in redis Using a block you can create your own criteria for lookup:

Example: let’s say there is a key named “foo”, and the value is a hash: :reading=>0

ret = session.scan_by do |x|

next unless x.kind_of? Hash
next unless x.key? :click

x[:click] == true

end

> :reading=>0}

If found return a hash of key => value If not found, return nil



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/redis_session.rb', line 287

def scan_by(&block)
  key   = ''
  value = ''
  @redis.keys('*').each do |x|
    next unless @redis.type(x) == 'string'
    
    value = Marshal.load(@redis.get(x)) rescue next # not really a ruby object
    if yield value
      key   = x
      break
    end
  end
  
  return nil if key.empty?
  
  { key => value }

rescue Redis::BaseConnectionError
  raise
rescue Exception #=> e
  # puts "exception: #{e}\n#{e.backtrace.join("\n")}"
  nil
end

#ttl(key) ⇒ Object

Examines how much time left to a key in seconds

key

The name of a key to check the ttl

returns

Returns the number of seconds left, or -1 if key does not exists or no ttl exists for it



189
190
191
192
193
194
195
196
197
# File 'lib/redis_session.rb', line 189

def ttl(key)
  a_key = make_key(key)
  @redis.ttl(a_key)

rescue Redis::BaseConnectionError
  raise
rescue Exception
  -1
end

#value?(key) ⇒ Boolean

Check if a key has a value

key

The name of the key to check

returns

true if exists or false otherwise

Returns:

  • (Boolean)


246
247
248
249
250
251
252
253
254
# File 'lib/redis_session.rb', line 246

def value?(key)
  a_key = make_key(key)
  @redis.get(a_key) != nil

rescue Redis::BaseConnectionError
  raise
rescue Exception
  false
end