Method: Readthis::Cache#delete_matched

Defined in:
lib/readthis/cache.rb

#delete_matched(pattern, options = {}) ⇒ Object

Delete all values that match a given pattern. The pattern must be defined using Redis compliant globs. The following examples are borrowed from the KEYS documentation:

  • ‘h?llo` matches hello, hallo and hxllo

  • ‘h*llo` matches hllo and heeeello

  • h[ae]llo matches hello and hallo, but not hillo

  • hllo` matches hallo, hbllo, … but not hello

  • h[a-b]llo matches hallo and hbllo

Note that delete_matched does not use the KEYS command, making it safe for use in production.

Examples:

Delete all ‘cat’ keys


cache.delete_matched('*cats') #=> 47
cache.delete_matched('*dogs') #=> 0

Parameters:

  • pattern (String)

    The glob pattern for matching keys

  • [String] (Hash)

    a customizable set of options

  • [Number] (Hash)

    a customizable set of options



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/readthis/cache.rb', line 156

def delete_matched(pattern, options = {})
  namespaced = namespaced_key(pattern, merged_options(options))

  invoke(:delete, pattern) do |store|
    cursor = nil
    count = options.fetch(:count, 1000)
    deleted = 0

    until cursor == '0'
      cursor, matched = store.scan(cursor || 0, match: namespaced, count: count)

      if matched.any?
        store.del(*matched)
        deleted += matched.length
      end
    end

    deleted
  end
end