Class: ThreadSafe::Cache

Inherits:
ConcurrentCacheBackend
  • Object
show all
Defined in:
lib/thread_safe/cache.rb

Constant Summary collapse

KEY_ERROR =

there is no KeyError in 1.8 mode

defined?(KeyError) ? KeyError : IndexError

Instance Method Summary collapse

Constructor Details

#initialize(options = nil, &block) ⇒ Cache

Returns a new instance of Cache.



23
24
25
26
27
28
29
30
31
32
# File 'lib/thread_safe/cache.rb', line 23

def initialize(options = nil, &block)
  if options.kind_of?(::Hash)
    validate_options_hash!(options)
  else
    options = nil
  end

  super(options)
  @default_proc = block
end

Instance Method Details

#[](key) ⇒ Object Also known as: get



34
35
36
37
38
39
40
41
42
# File 'lib/thread_safe/cache.rb', line 34

def [](key)
  if value = super
    value
  elsif @default_proc && !key?(key)
    @default_proc.call(self, key)
  else
    value
  end
end

#each_keyObject



87
88
89
# File 'lib/thread_safe/cache.rb', line 87

def each_key
  each_pair {|k, v| yield k}
end

#each_valueObject



91
92
93
# File 'lib/thread_safe/cache.rb', line 91

def each_value
  each_pair {|k, v| yield v}
end

#empty?Boolean

Returns:

  • (Boolean)


95
96
97
98
# File 'lib/thread_safe/cache.rb', line 95

def empty?
  each_pair {|k, v| return false}
  true
end

#fetch(key, default_value = NULL) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/thread_safe/cache.rb', line 47

def fetch(key, default_value = NULL)
  if NULL != (value = get_or_default(key, NULL))
    value
  elsif block_given?
    yield key
  elsif NULL != default_value
    default_value
  else
    raise KEY_ERROR, 'key not found'
  end
end

#keysObject



75
76
77
78
79
# File 'lib/thread_safe/cache.rb', line 75

def keys
  arr = []
  each_pair {|k, v| arr << k}
  arr
end

#marshal_dumpObject

Raises:

  • (TypeError)


106
107
108
109
110
111
# File 'lib/thread_safe/cache.rb', line 106

def marshal_dump
  raise TypeError, "can't dump hash with default proc" if @default_proc
  h = {}
  each_pair {|k, v| h[k] = v}
  h
end

#marshal_load(hash) ⇒ Object



113
114
115
116
# File 'lib/thread_safe/cache.rb', line 113

def marshal_load(hash)
  initialize
  populate_from(hash)
end

#put_if_absent(key, value) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/thread_safe/cache.rb', line 59

def put_if_absent(key, value)
  computed = false
  result = compute_if_absent(key) do
    computed = true
    value
  end
  computed ? nil : result
end

#sizeObject



100
101
102
103
104
# File 'lib/thread_safe/cache.rb', line 100

def size
  count = 0
  each_pair {|k, v| count += 1}
  count
end

#value?(value) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
71
72
73
# File 'lib/thread_safe/cache.rb', line 68

def value?(value)
  each_value do |v|
    return true if value.equal?(v)
  end
  false
end

#valuesObject



81
82
83
84
85
# File 'lib/thread_safe/cache.rb', line 81

def values
  arr = []
  each_pair {|k, v| arr << v}
  arr
end