Class: RedisLocker::ModelLocker

Inherits:
Locker
  • Object
show all
Includes:
RedisConnection
Defined in:
lib/redis_locker/model_locker.rb

Constant Summary

Constants inherited from Locker

Locker::NULL_SET_VALUE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Locker

#with_redis_lock

Constructor Details

#initialize(model_instance) ⇒ ModelLocker

Returns a new instance of ModelLocker.

Raises:



8
9
10
11
12
13
# File 'lib/redis_locker/model_locker.rb', line 8

def initialize(model_instance)
  raise Errors::NotModel unless model_instance.respond_to?(:id)

  @key_string = "LOCKER:#{model_instance.class}:#{model_instance.id}"
  super
end

Instance Attribute Details

#key_stringObject (readonly)

Returns the value of attribute key_string.



5
6
7
# File 'lib/redis_locker/model_locker.rb', line 5

def key_string
  @key_string
end

Instance Method Details

#lockObject



15
16
17
18
19
# File 'lib/redis_locker/model_locker.rb', line 15

def lock
  return false if locked?

  redis.sadd(@key_string, @instance_hash)
end

#lock!Object



21
22
23
24
25
# File 'lib/redis_locker/model_locker.rb', line 21

def lock!
  raise Errors::AlreadyLocked if locked?

  lock
end

#locked?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/redis_locker/model_locker.rb', line 27

def locked?
  redis.scard(@key_string) > 1 # it has to have NULL_SET_VALUE, otherwise redis will free key
end

#unlockObject



31
32
33
34
35
# File 'lib/redis_locker/model_locker.rb', line 31

def unlock
  return true unless locked?

  redis.srem(@key_string, @instance_hash)
end