Class: RedlockForCollection::Collection

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

Constant Summary collapse

DEFAULT_TTL =
10_000
DEFAULT_MIN_VALIDITY =
5_000
DEFAULT_KEY_METHOD =
'key'.freeze
DEFAULT_KEY_PREFIX =
'prefix'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(objects, options, pool) ⇒ Collection

Returns a new instance of Collection.



10
11
12
13
14
15
16
# File 'lib/redlock_for_collection/collection.rb', line 10

def initialize(objects, options, pool)
  @objects = objects
  @options = options
  @pool    = pool

  init_options
end

Instance Attribute Details

#objectsObject (readonly)

Returns the value of attribute objects.



8
9
10
# File 'lib/redlock_for_collection/collection.rb', line 8

def objects
  @objects
end

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/redlock_for_collection/collection.rb', line 8

def options
  @options
end

#poolObject (readonly)

Returns the value of attribute pool.



8
9
10
# File 'lib/redlock_for_collection/collection.rb', line 8

def pool
  @pool
end

Instance Method Details

#lock(&block) ⇒ Object



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
45
46
47
48
# File 'lib/redlock_for_collection/collection.rb', line 19

def lock(&block)
  locked_objects   = []
  unlocked_objects = []

  locks_info         = []
  expired_locks_info = []

  @objects.each do |object|
    @pool.with do |redlock|
      lock_info = redlock.lock(build_key_for(object), @options[:ttl])

      # Check if ttl is enough
      if lock_info && (lock_info[:validity] > (@options[:min_validity]))
        locked_objects << object
        locks_info     << lock_info
      else
        expired_locks_info << lock_info if lock_info
        unlocked_objects   << object
      end
    end
  end

  begin
    block.yield(locked_objects, unlocked_objects)
  ensure
    # Release the all acquired locks
    unlock(expired_locks_info)
    unlock(locks_info)
  end
end