Class: BackgroundCache::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Client

Returns a new instance of Client.



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/background_cache/client.rb', line 6

def initialize(root)
  if File.exists?(yaml = "#{root}/config/background_cache.yml")
    options = YAML.load(File.read(yaml))
  else
    puts "\nFAIL: config/background_cache.yml not found"
    shutdown
  end

  @redis_1 = Redis.connect(:url => "redis://#{options['redis']}")
  @redis_2 = Redis.connect(:url => "redis://#{options['redis']}")
end

Instance Attribute Details

#redis_1Object (readonly)

Returns the value of attribute redis_1.



4
5
6
# File 'lib/background_cache/client.rb', line 4

def redis_1
  @redis_1
end

#redis_2Object (readonly)

Returns the value of attribute redis_2.



4
5
6
# File 'lib/background_cache/client.rb', line 4

def redis_2
  @redis_2
end

Instance Method Details

#cache(options) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/background_cache/client.rb', line 18

def cache(options)
  wait = options.delete(:wait)
  subscribe_to = options[:channel] = Digest::SHA1.hexdigest("#{rand}")
  options = Yajl::Encoder.encode(options)
  response = nil

  if wait != false
    Timeout.timeout(60) do
      @redis_1.subscribe("background_cache:response:#{subscribe_to}") do |on|
        on.subscribe do |channel, subscriptions|
          @redis_2.rpush "background_cache:request", options
        end

        on.message do |channel, message|
          if message.include?('[SUCCESS]')
            response = true
            @redis_1.unsubscribe
          end
        end
      end
    end
  else
    @redis_1.rpush "background_cache:request", options
  end

  response
end

#queuedObject



46
47
48
49
50
51
# File 'lib/background_cache/client.rb', line 46

def queued
  queues = @redis_2.keys 'background_cache:queue:*'
  queues.collect do |q|
    Hash[*eval(q['background_cache:queue:'.length..-1]).flatten]
  end
end