File: pattern_cache.rb

package info (click to toggle)
ruby-mustermann19 0.4.3%2Bgit20160621-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 756 kB
  • ctags: 445
  • sloc: ruby: 7,197; makefile: 3
file content (49 lines) | stat: -rw-r--r-- 1,480 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
49
require 'set'
require 'thread'
require 'mustermann'

module Mustermann
  # A simple, persistent cache for creating repositories.
  #
  # @example
  #   require 'mustermann/pattern_cache'
  #   cache = Mustermann::PatternCache.new
  #   
  #   # use this instead of Mustermann.new
  #   pattern = cache.create_pattern("/:name", type: :rails)
  #
  # @note
  #   {Mustermann::Pattern.new} (which is used by {Mustermann.new}) will reuse instances that have
  #   not yet been garbage collected. You only need an extra cache if you do not keep a reference to
  #   the patterns around.
  #
  # @api private
  class PatternCache
    # @param [Hash] pattern_options default options used for {#create_pattern}
    def initialize(pattern_options = {})
      @cached          = Set.new
      @mutex           = Mutex.new
      @pattern_options = pattern_options
    end

    # @param (see Mustermann.new)
    # @return (see Mustermann.new)
    # @raise (see Mustermann.new)
    # @see Mustermann.new
    def create_pattern(string, pattern_options = {})
      pattern = Mustermann.new(string, @pattern_options.merge(pattern_options))
      @mutex.synchronize { @cached.add(pattern) } unless @cached.include? pattern
      pattern
    end

    # Removes all pattern instances from the cache.
    def clear
      @mutex.synchronize { @cached.clear }
    end

    # @return [Integer] number of currently cached patterns
    def size
      @mutex.synchronize { @cached.size }
    end
  end
end