class Sideroo::Enumerator

Attributes

filters[R]
limit[R]
redis_client[R]
search_pattern[R]
type_klass[R]

Public Class Methods

new(type_klass:, filters:, limit: -1) click to toggle source
# File lib/sideroo/enumerator.rb, line 12
def initialize(type_klass:, filters:, limit: -1)
  @type_klass = type_klass
  @limit = limit
  @redis_client = redis_client || Sideroo.redis_client
  @filters = stringify_keys(filters)

  @search_pattern = build_search_pattern
end

Public Instance Methods

count() click to toggle source
# File lib/sideroo/enumerator.rb, line 49
def count
  count = 0
  each_key { count += 1 }
  count
end
each() { |item| ... } click to toggle source
# File lib/sideroo/enumerator.rb, line 21
def each
  cursor = nil
  count = 0

  each_key do |key|
    item = type_klass.new(key)
    yield(item)
  end
end
each_key() { |key| ... } click to toggle source
# File lib/sideroo/enumerator.rb, line 31
def each_key
  cursor = nil
  count = 0

  until cursor.to_s == '0'
    cursor ||= 0
    cursor, keys = redis_client.scan(cursor, match: search_pattern)

    keys.each do |key|
      break if exceed_limit?(count)
      next unless regex_matched?(key)

      count += 1
      yield(key)
    end
  end
end
to_a() click to toggle source
# File lib/sideroo/enumerator.rb, line 55
def to_a
  map { |item| item }
end

Private Instance Methods

build_search_pattern() click to toggle source
# File lib/sideroo/enumerator.rb, line 69
def build_search_pattern
  search_pattern = type_klass.key_pattern

  type_klass.key_attributes.each do |attr|
    value = filters[attr]
    value = value.nil? ? '*' : value.to_s

    term = "{#{attr}}"
    search_pattern = search_pattern.gsub(term, value.to_s)
  end
  search_pattern
end
exceed_limit?(count) click to toggle source
# File lib/sideroo/enumerator.rb, line 61
def exceed_limit?(count)
  limit >= 0 && count > limit
end
regex_matched?(key) click to toggle source
# File lib/sideroo/enumerator.rb, line 65
def regex_matched?(key)
  key =~ type_klass.key_regex
end
stringify_keys(raw_attr_map) click to toggle source
# File lib/sideroo/enumerator.rb, line 82
def stringify_keys(raw_attr_map)
  raw_attr_map.map { |k, v| [k.to_s, v] }.to_h
end