refreshing_cache 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 4cff5afd7bfdb705da3ed12b2ac36492efe2be9e
4
+ data.tar.gz: ae5b1fab4134d77fc795d47d8b2447d83b90b2e9
5
+ SHA512:
6
+ metadata.gz: 00472cf7709777ef9e16e85b680c142e61642123d83aeb7c4abbdbd264772d0ecfc135dcd0d3c767eb20f214f11aadec5aa176bdf17b57508ae6133bc1ed1efd
7
+ data.tar.gz: ac01f7da301cdaaaf60b9141419527c2c7d03c9f43e89c3bd8ffb8c016e62888690e321330271105d425b2c4b1f2524ccd62603e4483caf4a0218c70c955228b
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in refreshing_cache.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Chris Schneider
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # RefreshingCache
2
+
3
+ *Motivation:* We have a background job that unpredictably sets a database row
4
+ that the application needs to be aware of on a regular, but delayed basis. We
5
+ can't afford to check for an update every request, and the processing the app
6
+ needs to do when it does change is substantial, so we don't want to toss the
7
+ cache unnecessarily.
8
+
9
+ *What this is:* A hash wrapper that lets you set a timeout, a checking proc, and
10
+ a refresh proc.
11
+
12
+ * When a value isn't present, the refersh proc runs to populate the cache
13
+ * When the timeout gets hit, the check_proc runs to see if a refresh is
14
+ actually required (just because it timed out doesn't mean the cache needs to be
15
+ tossed)
16
+
17
+
18
+ ## Installation
19
+
20
+ Add this line to your application's Gemfile:
21
+
22
+ gem 'refreshing_cache'
23
+
24
+ And then execute:
25
+
26
+ $ bundle
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install refreshing_cache
31
+
32
+ ## Usage
33
+
34
+ ```ruby
35
+ cache = RefreshingCache.new(timeout: 60,
36
+ check_proc: ->(key, last_refreshed) { Post.find_by_key(key).updated_at > last_refreshed },
37
+ value_proc: ->(key, last_refreshed) { Post.find_by_key(key).expensive_render } )
38
+
39
+ cache["post1"] # => Cache miss - calls expensive_render to generate a value
40
+
41
+ cache["post1"] # => Hasn't hit 60 seconds yet, no db hit
42
+
43
+ sleep 60
44
+ cache["post1"] # => 60 second timer is up, hits db to check if the post has been updated. It hasn't. Serves cached value
45
+
46
+ update_post!
47
+ cache["post1"] # => Hasn't hit 60 seconds since last check, so no db hit. Our cache is unfortunately stale.
48
+
49
+ sleep 60
50
+ cache["post1"] # => Hits the db, finds the post has changed, and calls the expensive_render call and serves that result.
51
+ ```
52
+
53
+ ## Contributing
54
+
55
+ 1. Fork it ( http://github.com/cschneid/refreshing_cache/fork )
56
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
57
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
58
+ 4. Push to the branch (`git push origin my-new-feature`)
59
+ 5. Create new Pull Request
60
+
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ task :console do
4
+ require 'irb'
5
+ require 'irb/completion'
6
+ require 'refreshing_cache'
7
+ ARGV.clear
8
+ IRB.start
9
+ end
@@ -0,0 +1,43 @@
1
+ require 'delegate'
2
+
3
+ class RefreshingCache < DelegateClass(Hash)
4
+ VERSION = "1.0.0"
5
+
6
+ def initialize(timeout: timeout, check_proc: check_proc, value_proc: value_proc)
7
+ @timeout = timeout
8
+
9
+ @check_proc = check_proc
10
+ @refresh_proc = value_proc
11
+
12
+ # Stores key => timeout info
13
+ @timeouts = {}
14
+
15
+ # Actual underlying data we're caching
16
+ @hash = {}
17
+ super(@hash)
18
+ end
19
+
20
+ def [](key)
21
+ self[key] = refresh!(key) if regenerate_value?(key)
22
+ super
23
+ end
24
+
25
+ def refresh!(key)
26
+ val = refresh_proc.call(key, timeouts[key])
27
+ timeouts[key] = Time.now
28
+ val
29
+ end
30
+
31
+ protected
32
+ attr_reader :check_proc, :refresh_proc, :timeout, :timeouts
33
+
34
+ def regenerate_value?(key)
35
+ # No timeout info? We need to generate values.
36
+ return true unless timeouts.has_key?(key)
37
+
38
+ # If we've timed out, force a check
39
+ return false if timeouts[key] + timeout > Time.now
40
+
41
+ check_proc.call(key, timeouts[key])
42
+ end
43
+ end
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'refreshing_cache'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "refreshing_cache"
8
+ spec.version = RefreshingCache::VERSION
9
+ spec.authors = ["Chris Schneider"]
10
+ spec.email = ["chris@christopher-schneider.com"]
11
+ spec.summary = %q{A hash-like object that attempts to refresh the keys based on some rules}
12
+ spec.description = %q{A hash-like object that attempts to refresh the keys based on some rules.}
13
+ spec.homepage = ""
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.5"
22
+ spec.add_development_dependency "rake"
23
+
24
+ spec.add_development_dependency "rspec"
25
+ end
@@ -0,0 +1,76 @@
1
+ $: << File.dirname(__FILE__) + "../"
2
+ require 'refreshing_cache'
3
+
4
+ # Sorry for the sleeps, it's the easiest way to test this without overmocking.
5
+ describe RefreshingCache do
6
+ before do
7
+ @check_proc_return_value = true
8
+ @check_proc_call_count = 0
9
+ @value_proc_call_count = 0
10
+ end
11
+
12
+ let!(:timeout) { 0.3 }
13
+ let!(:check_proc) { ->(key, time) { @check_proc_call_count += 1; @check_proc_return_value } }
14
+ let!(:value_proc) { ->(key, time) { @value_proc_call_count += 1; "calculated_value_for_#{key}_#{@value_proc_call_count}" } }
15
+
16
+ subject(:cache) { RefreshingCache.new(timeout: timeout, check_proc: check_proc, value_proc: value_proc) }
17
+
18
+ describe "#[]" do
19
+ it "doesn't call check_proc if there is no cached value" do
20
+ cache["test"]
21
+ expect(@check_proc_call_count).to eq(0)
22
+ end
23
+
24
+ it "returns the value returned by the value_proc" do
25
+ expect(cache["test"]).to eq("calculated_value_for_test_1")
26
+ end
27
+
28
+ describe "with a cached value" do
29
+ before { cache["test"] }
30
+
31
+ # TODO: A more clever way to do this, probably by reaching in and tweaking the timeouts hash
32
+ def expire!(key)
33
+ sleep(0.5)
34
+ end
35
+
36
+ it "doesn't call the check_proc if the cached value is within the timeout" do
37
+ cache["test"]
38
+ expect(@check_proc_call_count).to eq(0)
39
+ end
40
+
41
+ it "doesn't call the value_proc if the cached value is within the timeout" do
42
+ cache["test"]
43
+ expect(@value_proc_call_count).to eq(1)
44
+ end
45
+
46
+ it "calls the check_proc if the timeout has expired" do
47
+ expire!("test")
48
+ cache["test"]
49
+ expect(@check_proc_call_count).to eq(1)
50
+ end
51
+
52
+ it "returns the value in the cache" do
53
+ expect(cache["test"]).to eq("calculated_value_for_test_1")
54
+ end
55
+
56
+ context "when the check proc returns true" do
57
+ before { @check_proc_return_value = true }
58
+
59
+ it "after expiration, it calls the value_proc" do
60
+ expire!("test")
61
+ cache["test"]
62
+ expect(@value_proc_call_count).to eq(2)
63
+ end
64
+
65
+ it "returns the new value_proc result" do
66
+ expire!("test")
67
+ expect(cache["test"]).to eq("calculated_value_for_test_2")
68
+ end
69
+ end
70
+
71
+ context "When the check proc returns false" do
72
+ before { @check_proc_return_value = false }
73
+ end
74
+ end
75
+ end
76
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: refreshing_cache
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Chris Schneider
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-05-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.5'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: A hash-like object that attempts to refresh the keys based on some rules.
56
+ email:
57
+ - chris@christopher-schneider.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - Gemfile
64
+ - LICENSE.txt
65
+ - README.md
66
+ - Rakefile
67
+ - lib/refreshing_cache.rb
68
+ - refreshing_cache.gemspec
69
+ - spec/refreshing_cache_spec.rb
70
+ homepage: ''
71
+ licenses:
72
+ - MIT
73
+ metadata: {}
74
+ post_install_message:
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ requirements: []
89
+ rubyforge_project:
90
+ rubygems_version: 2.2.2
91
+ signing_key:
92
+ specification_version: 4
93
+ summary: A hash-like object that attempts to refresh the keys based on some rules
94
+ test_files:
95
+ - spec/refreshing_cache_spec.rb