Class: TouchTouch::Redis

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

Instance Method Summary collapse

Constructor Details

#initializeRedis

Returns a new instance of Redis.



3
4
5
# File 'lib/touch_touch/redis.rb', line 3

def initialize
  @redis = ::Redis.new
end

Instance Method Details

#get(toucher_class, toucher_id, touch_alias, touchee_class) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/touch_touch/redis.rb', line 7

def get(toucher_class, toucher_id, touch_alias, touchee_class)
  toucher_class = toucher_class.to_s
  toucher_id = toucher_id.to_s
  touch_alias = touch_alias.to_s
  touchee_class = touchee_class.to_s
  touchee_id = touchee_id.to_s

  h = JSON.parse(@redis.get(toucher_class.to_s) || "{}")
  touchee_ids = h.
    try(:[], toucher_id).
    try(:[], touch_alias).
    try(:[], touchee_class)

  (touchee_ids || []).map(&:to_i)
end

#set(toucher_class, toucher_id, touch_alias, touchee_class, touchee_id, limit) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/touch_touch/redis.rb', line 23

def set(toucher_class, toucher_id, touch_alias, touchee_class, touchee_id, limit)
  toucher_class = toucher_class.to_s
  toucher_id = toucher_id.to_s
  touch_alias = touch_alias.to_s
  touchee_class = touchee_class.to_s
  touchee_id = touchee_id.to_s

  h = JSON.parse(@redis.get(toucher_class) || "{}")
  @redis.set(toucher_class, {}) if h.blank?

  h[toucher_id] = h[toucher_id] || {}
  h[toucher_id][touch_alias] = h[toucher_id][touch_alias] || {}
  h[toucher_id][touch_alias][touchee_class] = h[toucher_id][touch_alias][touchee_class] || []
  h[toucher_id][touch_alias][touchee_class] << touchee_id
  if h[toucher_id][touch_alias][touchee_class].length > limit
    h[toucher_id][touch_alias][touchee_class].shift
  end

  @redis.set(toucher_class, h.to_json)
end