class SimpleMutex::Helper

Constants

LIST_MODES

Public Class Methods

get(lock_key) click to toggle source
# File lib/simple_mutex/helper.rb, line 10
def get(lock_key)
  new.get(lock_key)
end
list(**options) click to toggle source
# File lib/simple_mutex/helper.rb, line 14
def list(**options)
  new.list(**options)
end

Public Instance Methods

get(lock_key) click to toggle source
# File lib/simple_mutex/helper.rb, line 19
def get(lock_key)
  raw_data = redis.get(lock_key)

  return if raw_data.nil?

  parsed_data = safe_parse(raw_data)

  {
    key: lock_key,
    value: parsed_data.nil? ? raw_data : parsed_data,
  }
end
list(mode: :default) click to toggle source

rubocop:disable Metrics/MethodLength, Style/HashEachMethods, Performance/CollectionLiteralInLoop

# File lib/simple_mutex/helper.rb, line 33
def list(mode: :default)
  check_mode(mode)

  result = []

  redis.keys.each do |lock_key|
    redis.watch(lock_key) do
      raw_data = redis.get(lock_key)

      unless raw_data.nil?
        parsed_data = safe_parse(raw_data)

        if parsed_data.nil?
          result << { key: lock_key, value: raw_data } if mode == :all
        else
          lock_type = parsed_data&.dig("payload", "type")

          if (mode == :all) ||
             (lock_type == "Job" && %i[job default].include?(mode)) ||
             (lock_type == "Batch" && %i[batch default].include?(mode))
            result << { key: lock_key, value: parsed_data }
          end
        end
      end

      redis.unwatch
    end
  end

  result
end

Private Instance Methods

check_mode(mode) click to toggle source

rubocop:enable Metrics/MethodLength, Style/HashEachMethods, Performance/CollectionLiteralInLoop

# File lib/simple_mutex/helper.rb, line 68
def check_mode(mode)
  return if LIST_MODES.include?(mode)
  raise ::SimpleMutex::Error, "invalid mode ( only [:job, :batch, :default, :all] allowed)."
end
redis() click to toggle source
# File lib/simple_mutex/helper.rb, line 73
def redis
  ::SimpleMutex.redis
end
safe_parse(raw_data) click to toggle source
# File lib/simple_mutex/helper.rb, line 77
def safe_parse(raw_data)
  JSON.parse(raw_data)
rescue JSON::ParserError
  nil
end