Module: Dev::PlateBarcode::CacheBarcodes

Included in:
PlateBarcode
Defined in:
lib/dev/plate_barcode/cache_barcodes.rb

Overview

When in development mode we were receiving concurrent requests for creating a barcode which produced a race condition where all concurrent requests were obtaining the same barcode. To avoid it this module implements a cache of barcodes so it should be able to support up to MAX_SIZE_CACHE concurrent requests which we expect should be enough for development.

Constant Summary collapse

MAX_SIZE_CACHE =
100

Instance Method Summary collapse

Instance Method Details

#barcode_in_cache?(barcode) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 46

def barcode_in_cache?(barcode)
  data_cache.include?(barcode)
end

#cache_barcode(barcode) ⇒ Object



40
41
42
43
44
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 40

def cache_barcode(barcode)
  resize_cache

  data_cache.push(barcode)
end

#data_cacheObject

Cache stored in a class property (in PlateBarcode)



27
28
29
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 27

def data_cache
  @data_cache ||= []
end

#dev_cache_get_next_barcodeObject

Obtains a new barcode and if the obtained barcode was obtained before (if it was cached) it will retry and obtain a new barcode



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 12

def dev_cache_get_next_barcode
  pos = 1
  next_barcode = nil
  loop do
    next_barcode = (Barcode.sequencescape22.order(id: :desc).first&.number || 9000) + pos
    pos += 1
    break unless barcode_in_cache?(next_barcode)
  end
  cache_barcode(next_barcode)
  next_barcode
end

#reset_cacheObject



31
32
33
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 31

def reset_cache
  @data_cache = []
end

#resize_cacheObject

Avoids the cache to grow out of the cache limits



36
37
38
# File 'lib/dev/plate_barcode/cache_barcodes.rb', line 36

def resize_cache
  @data_cache = data_cache.drop(1) if data_cache.length >= MAX_SIZE_CACHE
end