memory_cache 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 1b852238fe4c99abb21c7d4e17a5d0235610e993
4
+ data.tar.gz: 19a28888d448eb7e400e25cbfa457467bb60f869
5
+ SHA512:
6
+ metadata.gz: 37e3c7494952cf0e8a6c317c4bac43ebbbdb757631c49b9597f121056a8d68aa8182d59e7737bee98075492ae7b5a83da68e5271d6a407b67dc4ad1b8c038d25
7
+ data.tar.gz: aafaf7509991e83c9e4597281570e4fba51d15f4fd4304c14ea5b0bf1fc16b5245f0c0cd4e1b5bec396a2677281233f0e49236e3758d2473c66560679facee39
@@ -0,0 +1,22 @@
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
18
+ *.bundle
19
+ *.so
20
+ *.o
21
+ *.a
22
+ mkmf.log
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in memory_cache.gemspec
4
+ gemspec
5
+
6
+ group :development, :test do
7
+ gem 'rspec'
8
+ gem 'timecop'
9
+ end
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Niels Buus
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.
@@ -0,0 +1,68 @@
1
+ # MemoryCache
2
+
3
+ Cache the result of a ruby block within the ruby process for a finite period. Useful when you want to cache a few things, but don't want to bother with setting up a separate caching service like memcached.
4
+
5
+ Example:
6
+
7
+ # In an initializer
8
+ JsonCache = MemoryCache.new(minutes: 5)
9
+
10
+ # In your code
11
+ JsonCache.get(url) do
12
+ raw_json = open(url).read
13
+ JSON.parse(raw_json)
14
+ end
15
+
16
+ The block will be invoked the first time, but any subsequent calls to `get`in the next 5 minutes will ignore the block and just return the same value as the first invocation did.
17
+
18
+
19
+ ## Installation
20
+
21
+ Add this line to your application's Gemfile:
22
+
23
+ gem 'memory_cache'
24
+
25
+ And then execute:
26
+
27
+ $ bundle
28
+
29
+ Or install it yourself as:
30
+
31
+ $ gem install memory_cache
32
+
33
+ ## Usage
34
+
35
+ Load the gem and create a cache. Specify the cache duration through the initializer. `seconds`, `minutes`, `hours` and `days` are valid options.
36
+
37
+ cache = MemoryCache.new(minutes: 2, seconds: 30)
38
+
39
+ This creates a cache where objects expire after 150 seconds.
40
+
41
+ If you fail to provide any of the above keys, the initializer will raise an ArgumentError.
42
+
43
+ Unlike other cache libraries, memory_cache doesn't have a `set` method. Instead the `get` method also acts as a `set` method by passing a block.
44
+
45
+ cache.get('the_game')
46
+ => nil
47
+ cache.get('the_game') { "you just lost it".upcase }
48
+ => "YOU JUST LOST IT"
49
+ cache.get('the_game')
50
+ => "YOU JUST LOST IT"
51
+
52
+ # 2 minutes and 31 seconds later
53
+ cache.get('the_game')
54
+ => nil
55
+
56
+ ## Keep in mind
57
+
58
+ MemoryCache does nothing to clean up the cache. Expired values will remain the internal hash of MemoryCache until they are replaced by new invocation with a block.
59
+
60
+ If your key set is massive or your block return values are fatty, consider calling `clear` on the cache now and then or go for a more advanced caching solution.
61
+
62
+ ## Contributing
63
+
64
+ 1. Fork it ( https://github.com/[my-github-username]/memory_cache/fork )
65
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
66
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
67
+ 4. Push to the branch (`git push origin my-new-feature`)
68
+ 5. Create a new Pull Request
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,45 @@
1
+ # require "memory_cache/version"
2
+
3
+ class MemoryCache
4
+ VERSION = "1.0.0"
5
+
6
+ attr_accessor :ttl_in_seconds, :cache
7
+ private :cache
8
+
9
+ def initialize(options = {minutes: 5})
10
+ @cache = {}
11
+ @ttl_in_seconds = calculate_ttl_in_seconds(options)
12
+ end
13
+
14
+ def get(key, &block)
15
+ key = key.to_s
16
+ record = cache[key]
17
+ if record.nil? || record[:expires] < Time.now.to_i
18
+ if block_given?
19
+ cache[key] = {
20
+ object: block.call,
21
+ expires: Time.now.to_i + ttl_in_seconds
22
+ }
23
+ else
24
+ return nil
25
+ end
26
+ end
27
+ cache[key][:object]
28
+ end
29
+
30
+ def clear
31
+ @cache = {}
32
+ end
33
+
34
+ private
35
+
36
+ def calculate_ttl_in_seconds(options)
37
+ seconds = options.fetch(:seconds, 0)
38
+ seconds += options.fetch(:minutes, 0) * 60
39
+ seconds += options.fetch(:hours, 0) * 60 * 60
40
+ seconds += options.fetch(:days, 0) * 60 * 60 * 24
41
+ fail ArgumentError.new("No duration specifieed for cache") if seconds.zero?
42
+ seconds
43
+ end
44
+
45
+ end
@@ -0,0 +1,3 @@
1
+ module MemoryCache
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,21 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'memory_cache'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "memory_cache"
8
+ spec.version = MemoryCache::VERSION
9
+ spec.authors = ["Niels Buus"]
10
+ spec.email = ["nielsbuus@gmail.com"]
11
+ spec.summary = "Cache the results of expensive code for a fixed time in memory. Handy for slow web services."
12
+ spec.description = "Cache the result of a ruby block within the ruby process for a finite period. Useful when you want to cache a few things, but don't want to bother with setting up a separate caching service like memcached."
13
+ spec.homepage = "https://github.com/nielsbuus/memory_cache"
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
+ end
@@ -0,0 +1,81 @@
1
+ require_relative "../lib/memory_cache"
2
+ require "timecop"
3
+
4
+ describe MemoryCache do
5
+
6
+ let(:cache) { MemoryCache.new(minutes: 2) }
7
+ let(:slow_object) { double("slow").as_null_object }
8
+
9
+ it "caches the result of passed block when reading" do
10
+ expect(slow_object).to receive(:query).exactly(1).times
11
+
12
+ 3.times do
13
+ cache.get "slow_key" do
14
+ slow_object.query
15
+ end
16
+ end
17
+ end
18
+
19
+ it "invokes block when cached object has expired" do
20
+ Timecop.freeze
21
+
22
+ expect(slow_object).to receive(:query).exactly(2).times
23
+
24
+ cache.get "slow_key" do
25
+ slow_object.query
26
+ end
27
+
28
+ Timecop.travel(60) do
29
+ cache.get "slow_key" do
30
+ slow_object.query # Should use the cache
31
+ end
32
+ end
33
+
34
+ Timecop.travel(300) do
35
+ cache.get "slow_key" do
36
+ slow_object.query # Should bust the cache
37
+ end
38
+ end
39
+
40
+ end
41
+
42
+ it "returns the result of the first block until expiration" do
43
+ Timecop.freeze
44
+ result = cache.get("slow_key") { 9000 + 1 }
45
+ expect(result).to eql 9001
46
+
47
+ Timecop.travel(60) do
48
+ result = cache.get("slow_key") { "ignore me" }
49
+ expect(result).to eql 9001
50
+ end
51
+
52
+ Timecop.travel(180) do
53
+ result = cache.get("slow_key") { "try me" }
54
+ expect(result).to eql "try me"
55
+ end
56
+ end
57
+
58
+ it "fails if initiates without duration" do
59
+ expect {
60
+ MemoryCache.new({})
61
+ }.to raise_error(ArgumentError)
62
+ end
63
+
64
+ context "with no block" do
65
+
66
+ context "it reads from the cache even if no block is provided" do
67
+
68
+ it "returns nil when the cache key holds no value" do
69
+ expect(cache.get("something_slow")).to be_nil
70
+ end
71
+
72
+ it "returns the value, when the cache key holds a value" do
73
+ cache.get("something_slow") { "result" }
74
+ expect(cache.get("something_slow")).to eql "result"
75
+ end
76
+
77
+ end
78
+
79
+ end
80
+
81
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: memory_cache
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Niels Buus
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-08-12 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Cache the result of a ruby block within the ruby process for a finite
14
+ period. Useful when you want to cache a few things, but don't want to bother with
15
+ setting up a separate caching service like memcached.
16
+ email:
17
+ - nielsbuus@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - ".gitignore"
23
+ - Gemfile
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - lib/memory_cache.rb
28
+ - lib/memory_cache/version.rb
29
+ - memory_cache.gemspec
30
+ - spec/memory_cache_spec.rb
31
+ homepage: https://github.com/nielsbuus/memory_cache
32
+ licenses:
33
+ - MIT
34
+ metadata: {}
35
+ post_install_message:
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubyforge_project:
51
+ rubygems_version: 2.2.2
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: Cache the results of expensive code for a fixed time in memory. Handy for
55
+ slow web services.
56
+ test_files:
57
+ - spec/memory_cache_spec.rb