cached_record 0.1.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: 93cc1d0bfdf782350a6fff60b88abc1b8d5a8562
4
+ data.tar.gz: 1b6b13ba8e18d9c417a015c5715a48c88d493531
5
+ SHA512:
6
+ metadata.gz: 44b292a27fed4e2bf01eff14ea8ca9fd39c6241a03db518fa25d778cbc2ce4312cb3f80756e85996ab9c86f907de8b188f5f3c97a7da5dba11a577475081e75c
7
+ data.tar.gz: ed9dc9141708f4a5e7ba71dceb98403bd94f583b9dead3b01a05bf0e8a30f865b5269a38bcb5a89fbe836cc9cb8d4545d50618d70880ef7bdc3ca062e6e729c2
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ .DS_Store
2
+ .bundle
3
+ .rvmrc
4
+ Gemfile.lock
5
+ doc
6
+ log/*.log
7
+ pkg
8
+ test/coverage
data/.travis.yml ADDED
@@ -0,0 +1,11 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
4
+ - 1.9.3
5
+ services:
6
+ - memcached
7
+ - redis-server
8
+ before_script:
9
+ - 'printf "test:\n adapter: mysql2\n database: cached_record_test\n username: travis\n encoding: utf8" > config/database.yml'
10
+ - 'mysql -e "create database cached_record_test;"'
11
+ - 'mysql cached_record_test < db/cached_record.sql'
data/CHANGELOG.rdoc ADDED
@@ -0,0 +1,5 @@
1
+ = CachedRecord CHANGELOG
2
+
3
+ == Version 0.1.0 (February 18, 2014)
4
+
5
+ * Initial release
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
4
+
5
+ group :development, :test do
6
+ gem "cached_record", :path => "."
7
+ end
8
+
9
+ group :test do
10
+ gem "simplecov", :require => false
11
+ gem "minitest"
12
+ gem "mocha"
13
+ end
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2014 Paul Engel
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,391 @@
1
+ == CachedRecord {<img src="https://secure.travis-ci.org/archan937/cached_record.png"/>}[http://travis-ci.org/archan937/cached_record] {<img src="https://codeclimate.com/github/archan937/cached_record.png"/>}[https://codeclimate.com/github/archan937/cached_record]
2
+
3
+ Cache (and optionally memoize) ActiveRecord or DataMapper records in Redis or Memcached.
4
+
5
+ === Installation
6
+
7
+ ==== Using Bundler
8
+
9
+ Add CachedRecord in <tt>Gemfile</tt> as a gem dependency:
10
+
11
+ gem "cached_record"
12
+
13
+ Run the following in your console to install with Bundler:
14
+
15
+ $ bundle install
16
+
17
+ === Setting up development and test databases
18
+
19
+ Make sure you have the correct database config in +database.yml+ and run:
20
+
21
+ $ rake db:install
22
+
23
+ === Usage
24
+
25
+ ==== Set up CachedRecord
26
+
27
+ At startup, you need to invoke <tt>CachedRecord.setup</tt>. This method does the following:
28
+
29
+ * it preps <tt>ActiveRecord::Base</tt> and/or <tt>DataMapper::Resource</tt> (only when defined)
30
+ * it registers the available cache stores (Redis and/or Memcached)
31
+
32
+ In a Rails application, you can add a Ruby source file (e.g. <tt>cached_record.rb</tt>) within <tt>config/initializers</tt> for instance.
33
+
34
+ You can specify the available cache stores by passing either a Symbol (<tt>:redis</tt> and/or <tt>:memcached</tt> with default localhost settings) or a key / value pair (with custom server settings):
35
+
36
+ When using Redis at localhost:
37
+
38
+ CachedRecord.setup :redis
39
+
40
+ When using Redis at localhost and Memcached at another server:
41
+
42
+ CachedRecord.setup :redis, :memcached => {:host => "123.45.67.8", :port => 90}
43
+
44
+ ==== Specify cache structure and strategy
45
+
46
+ A record will not automatically be cached in a cache store. You have to make a choice whether to only serialize objects within the cache store or whether you want also memoize objects (which is much more performant but at the cost of extra memory usage).
47
+
48
+ Also, you can specify which attributes, associations and/or instance variables need to be cached.
49
+
50
+ ===== Cache strategy
51
+
52
+ As already mentioned, you will have to choose whether you only want to serialize objects within the cache store or whether you also want to memoize them.
53
+
54
+ ====== Serializing objects
55
+
56
+ To only serialize objects within the cache store, use the class method <tt>as_cache</tt>:
57
+
58
+ class Article < ActiveRecord::Base
59
+ as_cache :only => [:title]
60
+ end
61
+
62
+ When using <tt>DataMapper</tt>:
63
+
64
+ class Article
65
+ include DataMapper::Resource
66
+ property :id, Serial, :key => true
67
+ property :title, String
68
+ as_cache :only => [:title]
69
+ end
70
+
71
+ Please note that the <tt>id</tt> of a record will always be cached and that in previous examples both the <tt>id</tt> and <tt>title</tt> attributes will be cached.
72
+
73
+ When trying this out in the console (please note when the query hits occur):
74
+
75
+ [1] pry(main)> ActiveRecord::Base.logger = Logger.new STDOUT; nil
76
+ => nil
77
+ [2] pry(main)> a = Article.first
78
+ D, [2013-12-12T22:59:52.223555 #23583] DEBUG -- : Article Load (0.3ms) SELECT `articles`.* FROM `articles` ORDER BY `articles`.`id` ASC LIMIT 1
79
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: "Cache ORM instances to avoid database queries", author_id: 1, foo_id: 2, published_at: "2013-08-01 12:00:00", created_at: "2013-08-01 10:00:00", updated_at: "2013-08-01 11:00:00">
80
+ [3] pry(main)> a.as_cache_json
81
+ => {:id=>1, :title=>"Behold! It's CachedRecord!"}
82
+ [4] pry(main)> a.to_cache_json
83
+ => "{\"id\":1,\"title\":\"Behold! It's CachedRecord!\"}"
84
+ [5] pry(main)> Article.cached(1)
85
+ D, [2013-12-12T22:59:59.656254 #23583] DEBUG -- : Article Load (0.3ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 1 LIMIT 1
86
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: nil, author_id: nil, foo_id: nil, published_at: nil, created_at: nil, updated_at: nil>
87
+ [6] pry(main)> Article.cached(1).object_id == Article.cached(1).object_id
88
+ => false
89
+ [7] pry(main)> Article.cached(1).title
90
+ => "Behold! It's CachedRecord!"
91
+ [8] pry(main)> Redis.new.get "article.1"
92
+ => "{\"id\":1,\"title\":\"Behold! It's CachedRecord!\"}"
93
+ [9] pry(main)> Article.first.title
94
+ D, [2013-12-12T23:00:04.159257 #23583] DEBUG -- : Article Load (0.3ms) SELECT `articles`.* FROM `articles` ORDER BY `articles`.`id` ASC LIMIT 1
95
+ => "Behold! It's CachedRecord!"
96
+
97
+ I will only continue with <tt>ActiveRecord::Base</tt> instances within examples as using <tt>DataMapper</tt> is quite similar.
98
+
99
+ ====== Serializing and memoizing objects
100
+
101
+ For better performance at the cost of extra memory usage, use the class method <tt>as_memoized_cache</tt>:
102
+
103
+ class Article < ActiveRecord::Base
104
+ as_memoized_cache :only => [:title]
105
+ end
106
+
107
+ When trying this out in the console:
108
+
109
+ [1] pry(main)> ActiveRecord::Base.logger = Logger.new STDOUT; nil
110
+ => nil
111
+ [2] pry(main)> a = Article.first
112
+ D, [2013-12-12T23:01:29.387239 #23763] DEBUG -- : Article Load (0.3ms) SELECT `articles`.* FROM `articles` ORDER BY `articles`.`id` ASC LIMIT 1
113
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: "Cache ORM instances to avoid database queries", author_id: 1, foo_id: 2, published_at: "2013-08-01 12:00:00", created_at: "2013-08-01 10:00:00", updated_at: "2013-08-01 11:00:00">
114
+ [3] pry(main)> a.as_cache_json
115
+ => {:id=>1, :title=>"Behold! It's CachedRecord!"}
116
+ [4] pry(main)> a.to_cache_json
117
+ => "{\"id\":1,\"title\":\"Behold! It's CachedRecord!\"}"
118
+ [5] pry(main)> Article.cached(1)
119
+ D, [2013-12-12T23:01:36.061953 #23763] DEBUG -- : Article Load (0.3ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 1 LIMIT 1
120
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: nil, author_id: nil, foo_id: nil, published_at: nil, created_at: nil, updated_at: nil>
121
+ [6] pry(main)> Article.cached(1).object_id == Article.cached(1).object_id
122
+ => true
123
+ [7] pry(main)> Article.cached(1).title
124
+ => "Behold! It's CachedRecord!"
125
+ [8] pry(main)> Redis.new.get "article.1"
126
+ => "{\"id\":1,\"title\":\"Behold! It's CachedRecord!\"}@1386885696"
127
+ [9] pry(main)> Article.first.title
128
+ D, [2013-12-12T23:01:40.556263 #23763] DEBUG -- : Article Load (0.4ms) SELECT `articles`.* FROM `articles` ORDER BY `articles`.`id` ASC LIMIT 1
129
+ => "Behold! It's CachedRecord!"
130
+ [10] pry(main)> CachedRecord::Cache.send :cache
131
+ => {Dalli::Client=>{},
132
+ Redis=>
133
+ {"article.1"=>
134
+ {:instance=>
135
+ #<Article id: 1, title: "Behold! It's CachedRecord!", content: nil, author_id: nil, foo_id: nil, published_at: nil, created_at: nil, updated_at: nil>,
136
+ :epoch_time=>1386885696}}}
137
+
138
+ ===== Cache store
139
+
140
+ When having specified more than one cache store with <tt>CachedRecord.setup</tt>, you will have to pass which cache store you want to use for a specific record class.
141
+
142
+ Either pass <tt>:memcached</tt> or <tt>:redis</tt> as follows:
143
+
144
+ class Article < ActiveRecord::Base
145
+ as_memoized_cache :memcached, :only => [:title]
146
+ end
147
+
148
+ When having specified only one cache store, you can leave it out:
149
+
150
+ CachedRecord.setup :redis
151
+
152
+ class Article < ActiveRecord::Base
153
+ as_memoized_cache :only => [:title]
154
+ end
155
+
156
+ This serializes Article records within the Redis server.
157
+
158
+ ===== Attributes
159
+
160
+ You have control over which attributes have to be serialized. Pass the <tt>:only</tt> option. When you don't pass the option, all attributes will be included.
161
+
162
+ class Article < ActiveRecord::Base
163
+ as_cache
164
+ end
165
+
166
+ [1] pry(main)> Article.first.as_cache_json
167
+ => {:id=>1,
168
+ :title=>"Behold! It's CachedRecord!",
169
+ :content=>"Cache ORM instances to avoid database queries",
170
+ :published_at=>2013-08-01 12:00:00 +0200,
171
+ :created_at=>2013-08-01 10:00:00 +0200,
172
+ :updated_at=>2013-08-01 11:00:00 +0200}
173
+
174
+ ===== Associations
175
+
176
+ You can include associations by passing the <tt>:include</tt> option. When using the setup of <tt>script/console</tt>:
177
+
178
+ [1] pry(main)> ActiveRecord::Base.logger = Logger.new STDOUT; nil
179
+ => nil
180
+ [2] pry(main)> Article.cached(1).as_cache_json
181
+ D, [2013-12-12T23:54:54.729034 #25722] DEBUG -- : Article Load (0.4ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 1 LIMIT 1
182
+ D, [2013-12-12T23:54:54.746719 #25722] DEBUG -- : User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
183
+ D, [2013-12-12T23:54:54.787599 #25722] DEBUG -- : Comment Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`article_id` = 1
184
+ D, [2013-12-12T23:54:54.803960 #25722] DEBUG -- : Tag Load (0.4ms) SELECT `tags`.* FROM `tags` INNER JOIN `articles_tags` ON `tags`.`id` = `articles_tags`.`tag_id` WHERE `articles_tags`.`article_id` = 1
185
+ D, [2013-12-12T23:54:54.811653 #25722] DEBUG -- : User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
186
+ D, [2013-12-12T23:54:54.814919 #25722] DEBUG -- : Article Load (0.4ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`foo_id` = 1 ORDER BY `articles`.`id` ASC LIMIT 1
187
+ D, [2013-12-12T23:54:54.817261 #25722] DEBUG -- : Comment Load (0.3ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`id` = 1 LIMIT 1
188
+ D, [2013-12-12T23:54:54.818860 #25722] DEBUG -- : User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1
189
+ D, [2013-12-12T23:54:54.820553 #25722] DEBUG -- : User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
190
+ D, [2013-12-12T23:54:54.821601 #25722] DEBUG -- : Article Load (0.2ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`foo_id` = 2 ORDER BY `articles`.`id` ASC LIMIT 1
191
+ D, [2013-12-12T23:54:54.823996 #25722] DEBUG -- : Comment Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`id` = 2 LIMIT 1
192
+ D, [2013-12-12T23:54:54.825475 #25722] DEBUG -- : User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
193
+ D, [2013-12-12T23:54:54.828590 #25722] DEBUG -- : Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id` = 1 LIMIT 1
194
+ D, [2013-12-12T23:54:54.830137 #25722] DEBUG -- : Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id` = 2 LIMIT 1
195
+ => {:id=>1,
196
+ :title=>"Behold! It's CachedRecord!",
197
+ :author_id=>1,
198
+ :_comment_ids=>[1, 2],
199
+ :_tag_ids=>[1, 2]}
200
+ [3] pry(main)> Article.cached(1).as_cache_json
201
+ => {:id=>1,
202
+ :title=>"Behold! It's CachedRecord!",
203
+ :author_id=>1,
204
+ :_comment_ids=>[1, 2],
205
+ :_tag_ids=>[1, 2]}
206
+ [4] pry(main)> Article.cached(1).author
207
+ => #<User id: 1, name: "Paul Engel", description: nil, active: nil, created_at: nil, updated_at: nil>
208
+ [5] pry(main)> a = Article.cached(1)
209
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: nil, author_id: 1, foo_id: nil, published_at: nil, created_at: nil, updated_at: nil>
210
+ [6] pry(main)> a.author.object_id == a.comments[1].poster.object_id
211
+ => true
212
+
213
+ ===== Instance variables
214
+
215
+ Finally, you can cache instance variables. Pass the <tt>:memoize</tt> option. This can be a Symbol or a Hash.
216
+
217
+ When passing a Symbol, CachedRecord expects that a method with that name is defined and that it memoizes an instance variable with the same name (prefixed with a <tt>@</tt>):
218
+
219
+ class Article < ActiveRecord::Base
220
+ as_cache :memcached, :only => [], :memoize => [:random_array]
221
+ def random_array
222
+ @random_array ||= [rand(10)]
223
+ end
224
+ end
225
+
226
+ [1] pry(main)> Article.cached(1).random_array
227
+ => [2]
228
+ [2] pry(main)> Article.cached(1).random_array
229
+ => [2]
230
+ [3] pry(main)> Article.first.random_array
231
+ => [4]
232
+ [4] pry(main)> Article.first.random_array
233
+ => [0]
234
+ [5] pry(main)> Article.cached(1).random_array
235
+ => [2]
236
+ [6] pry(main)> Article.cached(1).random_array
237
+ => [2]
238
+ [7] pry(main)> Dalli::Client.new.get "article.1"
239
+ => "{\"id\":1,\"@random_array\":[2]}"
240
+
241
+ You should pass a Hash when the name of the method differs from the name of the corresponding instance variable:
242
+
243
+ class Article < ActiveRecord::Base
244
+ as_cache :memcached, :only => [], :memoize => {:random_array => :@rarray}
245
+ def random_array
246
+ @rarray ||= [rand(10)]
247
+ end
248
+ end
249
+
250
+ [1] pry(main)> Article.cached(1).random_array
251
+ => [5]
252
+ [2] pry(main)> Article.cached(1).random_array
253
+ => [5]
254
+ [3] pry(main)> Article.first.random_array
255
+ => [9]
256
+ [4] pry(main)> Article.first.random_array
257
+ => [7]
258
+ [5] pry(main)> Article.cached(1).random_array
259
+ => [5]
260
+ [6] pry(main)> Article.cached(1).random_array
261
+ => [5]
262
+ [7] pry(main)> Dalli::Client.new.get "article.1"
263
+ => "{\"id\":1,\"@rarray\":[5]}"
264
+
265
+ ===== Include root
266
+
267
+ Like in Rails, you can pass <tt>:include_root</tt> when parsing a record to JSON. It wraps the resulting hash with an extra key (the class name underscored).
268
+
269
+ You can also do this with <tt>CachedRecord</tt>:
270
+
271
+ class Article < ActiveRecord::Base
272
+ as_cache :only => [:title], :include_root => true
273
+ end
274
+
275
+ When trying this out in the console:
276
+
277
+ [1] pry(main)> Article.first.as_cache_json
278
+ => {:article=>{:id=>1, :title=>"Behold! It's CachedRecord!"}}
279
+
280
+ Namespaces are ignored at default:
281
+
282
+ module Blog
283
+ class Article < ActiveRecord::Base
284
+ as_cache :only => [:title], :include_root => true
285
+ end
286
+ end
287
+
288
+ [1] pry(main)> Blog::Article.first.as_cache_json
289
+ => {:article=>{:id=>1, :title=>"Behold! It's CachedRecord!"}}
290
+
291
+ You can override this behaviour by overriding the `cache_root` class method:
292
+
293
+ module Blog
294
+ class Article < ActiveRecord::Base
295
+ as_cache :only => [:title], :include_root => true
296
+ def self.cache_root
297
+ :"#{name.underscore.gsub("/", ".")}"
298
+ end
299
+ end
300
+ end
301
+
302
+ [1] pry(main)> Blog::Article.first.as_cache_json
303
+ => {:"blog.article"=>{:id=>1, :title=>"Behold! It's CachedRecord!"}}
304
+
305
+ ===== Expiration
306
+
307
+ You can specify the TTL (Time To Live) of a record by passing the <tt>:expire</tt> option:
308
+
309
+ class Article < ActiveRecord::Base
310
+ as_memoized_cache :redis, :only => [:title], :expire => 5.seconds
311
+ end
312
+
313
+ [1] pry(main)> puts Article.cached(1).object_id; sleep 4; puts Article.cached(1).object_id; sleep 2; puts Article.cached(1).object_id
314
+ 70311156481000
315
+ 70311156481000
316
+ 70311131970100
317
+ => nil
318
+
319
+ ===== Retaining
320
+
321
+ You can retain memoized instances for a specific period of time. This reduces cache store hits and thus is more performant.
322
+
323
+ class Article < ActiveRecord::Base
324
+ as_memoized_cache :redis, :only => [:title], :retain => 5.seconds
325
+ end
326
+
327
+ In this case, memoized <tt>Article</tt> instances are retained for at least 5 seconds.
328
+
329
+ == Using the console
330
+
331
+ As you probably already noticed, the <tt>CachedRecord</tt> repo is provided with a <tt>script/console</tt> command which you can use for development / testing purposes. Please note that you have to run a Redis server locally.
332
+
333
+ Run the following command in your console:
334
+
335
+ $ script/console
336
+ Loading CachedRecord development environment (0.1.0)
337
+ [1] pry(main)> a = Article.cached(1)
338
+ => #<Article id: 1, title: "Behold! It's CachedRecord!", content: nil, author_id: 1, foo_id: nil, published_at: nil, created_at: nil, updated_at: nil>
339
+ [2] pry(main)> a.object_id == Article.cached(1).object_id
340
+ => true
341
+
342
+ == Benchmarking
343
+
344
+ The <tt>CachedRecord</tt> repo is provided with several benchmarks. You can run them using <tt>rake benchmark</tt>.
345
+
346
+ ruby-2.0.0 paulengel:cached_record (master) $ rake benchmark
347
+ Benchmarking uncached instances (5000 times)
348
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 27.92s
349
+ Benchmarking cached instances (5000 times)
350
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 25.66s
351
+ Benchmarking memoized instances (5000 times)
352
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 1.52s
353
+ Benchmarking retained instances (5000 times)
354
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 0.41s
355
+ Benchmarking memoized instances (150000 times)
356
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 39.40s
357
+ Benchmarking retained instances (150000 times)
358
+ -> [++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++] 100.0% in 7.75s
359
+ Done.
360
+
361
+ As expected, <b>retaining instances is the fastest cache strategy</b> at the cost of extra memory usage and having stale instances (in this case for 10 seconds).
362
+
363
+ Be sure to have a Redis server running locally when running the Rake task.
364
+
365
+ == Testing
366
+
367
+ Run the following command for testing:
368
+
369
+ $ rake
370
+
371
+ You can also run a single test file:
372
+
373
+ $ ruby test/unit/test_cached_record.rb
374
+
375
+ Please note that you have to run both a Redis server and a Memcached server locally.
376
+
377
+ === TODO
378
+
379
+ * Improve cache expiration (expiration period, memoized instances, references)
380
+
381
+ === License
382
+
383
+ Copyright (c) 2014 Paul Engel, released under the MIT license
384
+
385
+ http://gettopup.com – http://github.com/archan937 – http://twitter.com/archan937 – {pm_engel@icloud.com}[mailto:pm_engel@icloud.com]
386
+
387
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
388
+
389
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
390
+
391
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env rake
2
+ require "bundler/gem_tasks"
3
+ require "rake/testtask"
4
+
5
+ task :default => :test
6
+
7
+ Rake::TestTask.new do |test|
8
+ test.pattern = "test/**/test_*.rb"
9
+ end
10
+
11
+ task :benchmark do
12
+ require_relative "benchmark/setup"
13
+
14
+ def benchmark(description, count, interval)
15
+ Redis.new.flushdb
16
+ puts "Benchmarking #{description} (#{count} times)"
17
+ puts "-> [#{"." * 100}] 0.0% in 0.0s"
18
+ t = Time.now
19
+ count.times do |i|
20
+ if i % interval == (interval - 1)
21
+ print "\e[A\e[K"
22
+ percentage = (i / count.to_f) * 100
23
+ puts "-> [#{("+" * percentage.ceil).ljust(100, ".")}] #{"%.1f" % percentage}% in #{"%.2f" % (Time.now - t)}s"
24
+ end
25
+ yield
26
+ end
27
+ end
28
+
29
+ count = 5000
30
+ benchmark "uncached instances", count, 10 do
31
+ article = Cached::Article.find 1
32
+ article.author.foo
33
+ article.comments[0].poster.foo
34
+ article.comments[1].poster.foo
35
+ end
36
+ benchmark "cached instances", count, 10 do
37
+ article = Cached::Article.cached 1
38
+ article.author.foo
39
+ article.comments[0].poster.foo
40
+ article.comments[1].poster.foo
41
+ end
42
+ benchmark "memoized instances", count, 50 do
43
+ article = Memoized::Article.cached 1
44
+ article.author.foo
45
+ article.comments[0].poster.foo
46
+ article.comments[1].poster.foo
47
+ end
48
+ benchmark "retained instances", count, 50 do
49
+ article = Retained::Article.cached 1
50
+ article.author.foo
51
+ article.comments[0].poster.foo
52
+ article.comments[1].poster.foo
53
+ end
54
+
55
+ count = 150000
56
+ benchmark "memoized instances", count, 50 do Memoized::Article.cached 1 end
57
+ benchmark "retained instances", count, 100 do Retained::Article.cached 1 end
58
+
59
+ puts "Done."
60
+ end
61
+
62
+ namespace :db do
63
+ task :install do
64
+ require "bundler"
65
+ Bundler.require
66
+ require "yaml"
67
+ require "active_record"
68
+
69
+ %w(development test).each do |environment|
70
+ puts "Installing #{environment} database..."
71
+ dbconfig = YAML.load_file(File.expand_path("../config/database.yml", __FILE__))[environment]
72
+ host, port, user, password, database = dbconfig.values_at *%w(host port user password database)
73
+ options = {:charset => "utf8", :collation => "utf8_unicode_ci"}
74
+
75
+ ActiveRecord::Base.establish_connection dbconfig.merge("database" => nil)
76
+ ActiveRecord::Base.connection.create_database dbconfig["database"], options
77
+
78
+ `#{
79
+ [
80
+ "mysql",
81
+ ("-h #{host}" unless host.blank?), ("-P #{port}" unless port.blank?),
82
+ "-u #{user || "root"}", ("-p#{password}" unless password.blank?),
83
+ "#{database} < db/cached_record.sql"
84
+ ].compact.join(" ")
85
+ }`
86
+ end
87
+
88
+ puts "Done."
89
+ end
90
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,77 @@
1
+ require "bundler"
2
+ Bundler.require :default, :development
3
+
4
+ require "active_record"
5
+
6
+ dbconfig = YAML.load_file(File.expand_path("../../config/database.yml", __FILE__))["development"]
7
+ ActiveRecord::Base.establish_connection dbconfig
8
+ ActiveRecord::Base.time_zone_aware_attributes = true
9
+ ActiveRecord::Base.default_timezone = :local
10
+
11
+ CachedRecord.setup :redis
12
+
13
+ module Cached
14
+ class Article < ActiveRecord::Base
15
+ self.table_name = "articles"
16
+ belongs_to :author, :class_name => "Cached::User", :foreign_key => "author_id"
17
+ has_many :comments, :class_name => "Cached::Comment", :foreign_key => "article_id"
18
+ as_cache :only => [:title], :include => [:author, :comments]
19
+ end
20
+
21
+ class User < ActiveRecord::Base
22
+ self.table_name = "users"
23
+ has_one :foo, :class_name => "Cached::Article", :foreign_key => "foo_id"
24
+ as_cache :only => [:name], :include => [:foo]
25
+ end
26
+
27
+ class Comment < ActiveRecord::Base
28
+ self.table_name = "comments"
29
+ belongs_to :article, :class_name => "Cached::Article", :foreign_key => "article_id"
30
+ belongs_to :poster, :class_name => "Cached::User", :foreign_key => "poster_id"
31
+ as_cache :only => [:content], :include => [:poster]
32
+ end
33
+ end
34
+
35
+ module Memoized
36
+ class Article < ActiveRecord::Base
37
+ self.table_name = "articles"
38
+ belongs_to :author, :class_name => "Memoized::User", :foreign_key => "author_id"
39
+ has_many :comments, :class_name => "Memoized::Comment", :foreign_key => "article_id"
40
+ as_memoized_cache :only => [:title], :include => [:author, :comments]
41
+ end
42
+
43
+ class User < ActiveRecord::Base
44
+ self.table_name = "users"
45
+ has_one :foo, :class_name => "Memoized::Article", :foreign_key => "foo_id"
46
+ as_memoized_cache :only => [:name], :include => [:foo]
47
+ end
48
+
49
+ class Comment < ActiveRecord::Base
50
+ self.table_name = "comments"
51
+ belongs_to :article, :class_name => "Memoized::Article", :foreign_key => "article_id"
52
+ belongs_to :poster, :class_name => "Memoized::User", :foreign_key => "poster_id"
53
+ as_memoized_cache :only => [:content], :include => [:poster]
54
+ end
55
+ end
56
+
57
+ module Retained
58
+ class Article < ActiveRecord::Base
59
+ self.table_name = "articles"
60
+ belongs_to :author, :class_name => "Retained::User", :foreign_key => "author_id"
61
+ has_many :comments, :class_name => "Retained::Comment", :foreign_key => "article_id"
62
+ as_memoized_cache :only => [:title], :include => [:author, :comments], :retain => 10.seconds
63
+ end
64
+
65
+ class User < ActiveRecord::Base
66
+ self.table_name = "users"
67
+ has_one :foo, :class_name => "Retained::Article", :foreign_key => "foo_id"
68
+ as_memoized_cache :only => [:name], :include => [:foo], :retain => 10.seconds
69
+ end
70
+
71
+ class Comment < ActiveRecord::Base
72
+ self.table_name = "comments"
73
+ belongs_to :article, :class_name => "Retained::Article", :foreign_key => "article_id"
74
+ belongs_to :poster, :class_name => "Retained::User", :foreign_key => "poster_id"
75
+ as_memoized_cache :only => [:content], :include => [:poster], :retain => 10.seconds
76
+ end
77
+ end
@@ -0,0 +1,26 @@
1
+ # -*- encoding: utf-8 -*-
2
+ require File.expand_path("../lib/cached_record/version", __FILE__)
3
+
4
+ Gem::Specification.new do |gem|
5
+ gem.authors = ["Paul Engel"]
6
+ gem.email = ["pm_engel@icloud.com"]
7
+ gem.summary = %q{Cache (and optionally memoize) ActiveRecord or DataMapper records in Redis or Memcached}
8
+ gem.description = %q{Cache (and optionally memoize) ActiveRecord or DataMapper records in Redis or Memcached}
9
+ gem.homepage = "https://github.com/archan937/cached_record"
10
+
11
+ gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
12
+ gem.files = `git ls-files`.split("\n")
13
+ gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
14
+ gem.name = "cached_record"
15
+ gem.require_paths = ["lib"]
16
+ gem.version = CachedRecord::VERSION
17
+
18
+ gem.add_dependency "dalli"
19
+ gem.add_dependency "redis"
20
+ gem.add_development_dependency "rake"
21
+ gem.add_development_dependency "pry"
22
+ gem.add_development_dependency "mysql2"
23
+ gem.add_development_dependency "activerecord"
24
+ gem.add_development_dependency "dm-mysql-adapter"
25
+ gem.add_development_dependency "data_mapper"
26
+ end