Sha256: 84f5bb290632c4ef7746f3dafc6bf54be87adcdc96cf3a34f9c765d31b3858c0

Contents?: true

Size: 1.87 KB

Versions: 8

Compression:

Stored size: 1.87 KB

Contents

module Plezi

	module Base
		module AutoRedis
			@redis_locker ||= Mutex.new
			@redis = @redis_sub_thread = nil
			module_function
			def inner_init_redis
				return false unless ENV['PL_REDIS_URL'] && defined?(::Redis)
				@redis_locker.synchronize do
					return @redis if (@redis_sub_thread && @redis_sub_thread.alive?) && @redis # repeat the test once syncing is done.
					@redis.quit if @redis
					@redis = ::Redis.new(url: ENV['PL_REDIS_URL'])
					raise "Redis connction failed for: #{ENV['PL_REDIS_URL']}" unless @redis
					@redis_sub_thread = Thread.new do
						begin
							::Redis.new(url: ENV['PL_REDIS_URL']).subscribe(Plezi::Settings.redis_channel_name, Plezi::Settings.uuid) do |on|
								on.message do |channel, msg|
									::Plezi::Base::WSObject.forward_message ::Plezi::Base::WSObject.translate_message(msg)
								end
							end
						rescue => e
							Iodine.error e
							retry
						end
					end
					@redis
				end
			end
			def get_redis
				return @redis if (@redis_sub_thread && @redis_sub_thread.alive?) && @redis
				inner_init_redis
			end
			def away? server
				return true unless get_redis
				@redis.pubsub('CHANNELS', server).empty?				
			end
		end
	end

	module_function

	# Reviews the Redis connection, sets it up if it's missing and returns the Redis connection.
	#
	# A Redis connection will be automatically created if the `ENV['PL_REDIS_URL']` is set.
	# for example:
	#      ENV['PL_REDIS_URL'] = ENV['REDISCLOUD_URL']`
	# or
	#      ENV['PL_REDIS_URL'] = "redis://:password@my.host:6379/0"
	#
	# Accepts an optional block that will receive the Redis connection object. i.e.
	#
	#      Plezi.redis {|r| r.connected? }
	#
	# Returns the Redis object or the block's returned value (if a block is provided).
	def redis
		if r = Plezi::Base::AutoRedis.get_redis
			return (block_given? ? yield(r) : r)
		end
		false
	end
	alias :redis_connection :redis
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
plezi-0.12.22 lib/plezi/common/redis.rb
plezi-0.12.21 lib/plezi/common/redis.rb
plezi-0.12.20 lib/plezi/common/redis.rb
plezi-0.12.19 lib/plezi/common/redis.rb
plezi-0.12.18 lib/plezi/common/redis.rb
plezi-0.12.17 lib/plezi/common/redis.rb
plezi-0.12.16 lib/plezi/common/redis.rb
plezi-0.12.15 lib/plezi/common/redis.rb