background_cache 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (32) hide show
  1. data/MIT-LICENSE +18 -0
  2. data/README.markdown +64 -0
  3. data/Rakefile +23 -0
  4. data/init.rb +1 -0
  5. data/lib/background_cache/config.rb +121 -0
  6. data/lib/background_cache/controller.rb +57 -0
  7. data/lib/background_cache/helper.rb +25 -0
  8. data/lib/background_cache.rb +51 -0
  9. data/rails/init.rb +5 -0
  10. data/require.rb +47 -0
  11. data/spec/background_cache_spec.rb +96 -0
  12. data/spec/fixtures/rails/app/controllers/application_controller.rb +14 -0
  13. data/spec/fixtures/rails/app/helpers/application_helper.rb +3 -0
  14. data/spec/fixtures/rails/app/views/application/test_1.html.erb +1 -0
  15. data/spec/fixtures/rails/app/views/application/test_2.html.erb +2 -0
  16. data/spec/fixtures/rails/app/views/layouts/application.html.erb +4 -0
  17. data/spec/fixtures/rails/config/boot.rb +110 -0
  18. data/spec/fixtures/rails/config/environment.rb +45 -0
  19. data/spec/fixtures/rails/config/environments/development.rb +17 -0
  20. data/spec/fixtures/rails/config/environments/production.rb +28 -0
  21. data/spec/fixtures/rails/config/environments/test.rb +28 -0
  22. data/spec/fixtures/rails/config/initializers/backtrace_silencers.rb +7 -0
  23. data/spec/fixtures/rails/config/initializers/inflections.rb +10 -0
  24. data/spec/fixtures/rails/config/initializers/mime_types.rb +5 -0
  25. data/spec/fixtures/rails/config/initializers/new_rails_defaults.rb +21 -0
  26. data/spec/fixtures/rails/config/initializers/session_store.rb +15 -0
  27. data/spec/fixtures/rails/config/locales/en.yml +5 -0
  28. data/spec/fixtures/rails/config/routes.rb +48 -0
  29. data/spec/fixtures/rails/lib/background_cache_config.rb +15 -0
  30. data/spec/spec_helper.rb +7 -0
  31. data/tasks/background_cache.rake +4 -0
  32. metadata +104 -0
data/MIT-LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Copyright (c) 2009 Winton Welsh
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.markdown ADDED
@@ -0,0 +1,64 @@
1
+ BackgroundCache
2
+ ===============
3
+
4
+ Bust caches before your users do (in your Rails app).
5
+
6
+ Requirements
7
+ ------------
8
+
9
+ <pre>
10
+ sudo gem install background_cache
11
+ </pre>
12
+
13
+ ### config/environment.rb
14
+
15
+ <pre>
16
+ config.gem 'background_cache'
17
+ </pre>
18
+
19
+ Dynamic Configuration
20
+ ---------------------
21
+
22
+ Create *lib/background\_cache\_config.rb*:
23
+
24
+ <pre>
25
+ BackgroundCache::Config.new do
26
+
27
+ # Configure a background cache in one call
28
+
29
+ Tag::League.find(:all).each do |tag|
30
+ cache(
31
+ # Route params
32
+ :controller => 'sections',
33
+ :action => 'teams',
34
+ :tag => tag.permalink,
35
+
36
+ # Background cache options
37
+ :group => 'every_hour',
38
+ :layout => false,
39
+ :only => "sections_teams_#{tag.permalink}"
40
+ )
41
+ end
42
+
43
+ # Configure using block methods
44
+
45
+ group('every_hour').layout(false).only("sections_teams_#{tag.permalink}") do
46
+ Tag::League.find(:all).each do |tag|
47
+ cache("/#{tag.permalink}")
48
+ end
49
+ end
50
+ end
51
+ </pre>
52
+
53
+ The <code>cache</code> method takes route parameters or a path.
54
+
55
+ The <code>only</code> and <code>except</code> methods/options take fragment ids or arrays of fragment ids.
56
+
57
+ If no fragment is specified, all of the action's caches will regenerate.
58
+
59
+ Rake task
60
+ ---------
61
+
62
+ Add <code>rake background_cache</code> to cron. All cache configurations are busted every time it is run.
63
+
64
+ To run a specific group of caches, run <code>rake background\_cache[every\_hour]</code> (as per the example above).
data/Rakefile ADDED
@@ -0,0 +1,23 @@
1
+ require "#{File.dirname(__FILE__)}/require"
2
+ Require.rakefile!
3
+
4
+ # You can delete this after you use it
5
+ desc "Rename project"
6
+ task :rename do
7
+ name = ENV['NAME'] || File.basename(Dir.pwd)
8
+ begin
9
+ dir = Dir['**/gem_template*']
10
+ from = dir.pop
11
+ if from
12
+ rb = from.include?('.rb')
13
+ to = File.dirname(from) + "/#{name}#{'.rb' if rb}"
14
+ FileUtils.mv(from, to)
15
+ end
16
+ end while dir.length > 0
17
+ Dir["**/*"].each do |path|
18
+ next if path.include?('Rakefile')
19
+ if File.file?(path)
20
+ `sed -i "" 's/gem_template/#{name}/g' #{path}`
21
+ end
22
+ end
23
+ end
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + "/rails/init"
@@ -0,0 +1,121 @@
1
+ require 'digest/sha2'
2
+
3
+ module BackgroundCache
4
+ class Config
5
+ def initialize(&block)
6
+ @@caches = []
7
+ self.instance_eval &block
8
+ end
9
+ def cache(options)
10
+ # Method-style config
11
+ @options ||= {}
12
+ options = @options.merge(options)
13
+ # Store the cache options
14
+ @@caches.push({
15
+ :except => options.delete(:except),
16
+ :group => options.delete(:group),
17
+ :layout => options.delete(:layout),
18
+ :only => options.delete(:only),
19
+ :path => options.delete(:path),
20
+ :params => options
21
+ })
22
+ end
23
+ def except(value, &block)
24
+ set_option(:except, value, &block)
25
+ end
26
+ def group(value, &block)
27
+ set_option(:group, value, &block)
28
+ end
29
+ def layout(value, &block)
30
+ set_option(:layout, value, &block)
31
+ end
32
+ def only(value, &block)
33
+ set_option(:only, value, &block)
34
+ end
35
+ def set_option(key, value, &block)
36
+ @options ||= {}
37
+ @options[key] = value
38
+ if block
39
+ yield
40
+ @options = {}
41
+ end
42
+ self
43
+ end
44
+ # Find cache config from params
45
+ def self.from_controller(controller)
46
+ from_controller_and_fragment(controller)
47
+ end
48
+ def self.from_controller_and_fragment(controller, fragment={})
49
+ params = controller.params
50
+ params.delete 'background_cache'
51
+ path = controller.request.env['REQUEST_URI'].gsub(/[&?]background_cache=.+/, '')
52
+ if defined?(@@caches) && !@@caches.empty?
53
+ @@caches.detect do |item|
54
+ # Basic params match (action, controller, etc)
55
+ (
56
+ (item[:path] && item[:path] == path) ||
57
+ item[:params] == params.symbolize_keys
58
+ ) &&
59
+ (
60
+ # No fragment specified
61
+ fragment.empty? ||
62
+ (
63
+ (
64
+ # :only not defined
65
+ !item[:only] ||
66
+ # :only matches fragment
67
+ item[:only] == fragment ||
68
+ (
69
+ # :only is an array
70
+ item[:only].respond_to?(:index) &&
71
+ # :only includes matching fragment
72
+ item[:only].include?(fragment)
73
+ )
74
+ ) &&
75
+ (
76
+ # :except not defined
77
+ !item[:except] ||
78
+ # :except not explicitly named
79
+ item[:except] != fragment ||
80
+ (
81
+ # :except is an array
82
+ item[:except].respond_to?(:index) &&
83
+ # :except does not include matching fragment
84
+ !item[:except].include?(fragment)
85
+ )
86
+ )
87
+ )
88
+ )
89
+ end
90
+ end
91
+ end
92
+ def self.caches
93
+ @@caches
94
+ end
95
+ def self.key
96
+ Digest::SHA256.hexdigest("--#{Time.now}--#{rand}--")
97
+ end
98
+ def self.load!
99
+ load RAILS_ROOT + "/lib/background_cache_config.rb"
100
+ end
101
+ def self.unload!
102
+ @@caches = []
103
+ end
104
+ # Unique cache id for storing last expired time
105
+ def self.unique_cache_id(cache)
106
+ id = []
107
+ join = lambda do |k, v|
108
+ id << (k.nil? || v.nil? ?
109
+ nil : [ k, v ].collect { |kv| kv.to_s.gsub(/\W/, '_') }.join('-')
110
+ )
111
+ end
112
+ cache[:params].each do |key, value|
113
+ join.call(key, value)
114
+ end
115
+ cache.each do |key, value|
116
+ join.call(key, value) unless key == :params
117
+ end
118
+ 'background_cache/' + id.compact.join('/')
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,57 @@
1
+ module BackgroundCache
2
+ module Controller
3
+ def self.included(base)
4
+ base.alias_method_chain :read_fragment, :background_cache
5
+ base.around_filter BackgroundCacheFilter.new
6
+ end
7
+
8
+ private
9
+
10
+ def read_fragment_with_background_cache(key, options=nil)
11
+ cache = BackgroundCache::Config.from_controller_and_fragment(self, key)
12
+ if cache
13
+ RAILS_DEFAULT_LOGGER.info "Cached fragment busted (read_fragment method): #{key}"
14
+ nil
15
+ else
16
+ read_fragment_without_background_cache(key, options)
17
+ end
18
+ end
19
+
20
+ class BackgroundCacheFilter
21
+ def before(controller)
22
+ @background_cache = {
23
+ :key => controller.params.delete("background_cache"),
24
+ :load => controller.params.delete("background_cache_load")
25
+ }
26
+ if @background_cache[:key]
27
+ # Secure filters
28
+ key = ::ActionController::Base.cache_store.read('background_cache/key')
29
+ # Turn off the layout if necessary
30
+ if @background_cache[:key] == key
31
+ cache = BackgroundCache::Config.from_controller(controller)
32
+ # Store current layout, then disable it
33
+ if cache && cache[:layout] == false
34
+ @background_cache[:layout] = controller.active_layout
35
+ controller.class.layout(false)
36
+ end
37
+ end
38
+ end
39
+ true
40
+ end
41
+ def after(controller)
42
+ # Restore layout
43
+ if @background_cache[:layout]
44
+ controller.class.layout(@background_cache[:layout])
45
+ end
46
+ if @background_cache[:load]
47
+ # Secure filters
48
+ key = ::ActionController::Base.cache_store.read('background_cache/key')
49
+ # Load the background cache config
50
+ if @background_cache[:load] == key
51
+ BackgroundCache::Config.load!
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,25 @@
1
+ module BackgroundCache
2
+ module Helper
3
+ def self.included(base)
4
+ base.alias_method_chain :cache, :background_cache
5
+ end
6
+ def cache_with_background_cache(name = {}, options = nil, &block)
7
+ cache = BackgroundCache::Config.from_controller_and_fragment(controller, name)
8
+ if cache
9
+ RAILS_DEFAULT_LOGGER.info "Cached fragment busted (cache block): #{name.inspect}"
10
+ # http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html
11
+ # http://api.rubyonrails.org/classes/ActionController/Caching/Fragments.html
12
+ # ActionController::Caching::Fragments#fragment_for (undocumented)
13
+ pos = output_buffer.length
14
+ block.call
15
+ output = [
16
+ "<!-- #{name.inspect} cached #{Time.now.strftime("%m/%d/%Y at %I:%M %p")} -->",
17
+ output_buffer[pos..-1]
18
+ ].join("\n")
19
+ @controller.write_fragment(name, output, options)
20
+ else
21
+ cache_without_background_cache(name, options, &block)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,51 @@
1
+ require File.expand_path("#{File.dirname(__FILE__)}/../require")
2
+ Require.lib!
3
+
4
+ module BackgroundCache
5
+
6
+ class AppInstance
7
+ include ActionController::UrlWriter
8
+ include Rack::Test::Methods
9
+ def app
10
+ ActionController::Dispatcher.new
11
+ end
12
+ end
13
+
14
+ def self.cache!(group=nil)
15
+ key, instance = boot
16
+ caches = BackgroundCache::Config.caches
17
+ caches.each do |cache|
18
+ next if group && cache[:group] != group
19
+ url = cache[:path] || instance.url_for(cache[:params].merge(:only_path => true))
20
+ puts "(#{cache[:group]}) #{url}"
21
+ instance.get(url + "#{url.include?('?') ? '&' : '?'}background_cache=#{key}")
22
+ end
23
+ end
24
+
25
+ def self.manual(url)
26
+ key, instance = boot
27
+ url = instance.url_for(url.merge(:only_path => true)) if url.respond_to?(:keys)
28
+ instance.get(url + "#{url.include?('?') ? '&' : '?'}background_cache=#{key}")
29
+ url
30
+ end
31
+
32
+ private
33
+
34
+ def self.boot
35
+ key = set_key!
36
+ instance = AppInstance.new
37
+ instance.get("/?background_cache_load=#{key}")
38
+ load RAILS_ROOT + "/lib/background_cache_config.rb"
39
+ [ key, instance ]
40
+ end
41
+
42
+ def self.set_key!
43
+ key = BackgroundCache::Config.key
44
+ ::ActionController::Base.cache_store.write('background_cache/key', key)
45
+ key
46
+ end
47
+ end
48
+
49
+ def BackgroundCache(url)
50
+ BackgroundCache.manual(url)
51
+ end
data/rails/init.rb ADDED
@@ -0,0 +1,5 @@
1
+ require File.expand_path("#{File.dirname(__FILE__)}/../require")
2
+ Require.rails_init!
3
+
4
+ ActionController::Base.send(:include, BackgroundCache::Controller)
5
+ ActionView::Helpers::CacheHelper.send(:include, BackgroundCache::Helper)
data/require.rb ADDED
@@ -0,0 +1,47 @@
1
+ require 'rubygems'
2
+ gem 'require'
3
+ require 'require'
4
+
5
+ Require do
6
+ gem :require, '=0.2.7'
7
+ gem(:'rack-test', '=0.5.3') { require 'rack/test' }
8
+ gem(:rake, '=0.8.7') { require 'rake' }
9
+ gem :rspec, '=1.3.0'
10
+
11
+ gemspec do
12
+ author 'Winton Welsh'
13
+ dependencies do
14
+ gem :'rack-test'
15
+ gem :require
16
+ end
17
+ email 'mail@wintoni.us'
18
+ name 'background_cache'
19
+ homepage "http://github.com/winton/#{name}"
20
+ summary "Bust caches before your users do"
21
+ version '0.1.0'
22
+ end
23
+
24
+ bin { require 'lib/background_cache' }
25
+
26
+ lib do
27
+ gem :'rack-test'
28
+ require 'lib/background_cache/config'
29
+ require 'lib/background_cache/controller'
30
+ require 'lib/background_cache/helper'
31
+ end
32
+
33
+ rails_init { require 'lib/background_cache' }
34
+
35
+ rakefile do
36
+ gem(:rake) { require 'rake/gempackagetask' }
37
+ gem(:rspec) { require 'spec/rake/spectask' }
38
+ require 'require/tasks'
39
+ end
40
+
41
+ spec_helper do
42
+ gem :'rack-test'
43
+ require 'require/spec_helper'
44
+ require 'pp'
45
+ require 'spec/fixtures/rails/config/environment'
46
+ end
47
+ end
@@ -0,0 +1,96 @@
1
+ require File.dirname(__FILE__) + "/spec_helper"
2
+
3
+ COMMENT_REGEX = /<!-- ".+" cached .+ -->\n/
4
+
5
+ describe BackgroundCache do
6
+
7
+ include Rack::Test::Methods
8
+
9
+ def app
10
+ ActionController::Dispatcher.new
11
+ end
12
+
13
+ before(:each) do
14
+ BackgroundCache::Config.unload!
15
+ end
16
+
17
+ describe :Controller do
18
+
19
+ it "should call load! with background_cache_load parameter" do
20
+ key = BackgroundCache.set_key!
21
+ BackgroundCache::Config.should_receive(:load!)
22
+ get('/', { :background_cache_load => key })
23
+ end
24
+
25
+ it "should call from_controller with background_cache parameter" do
26
+ key = BackgroundCache.set_key!
27
+ BackgroundCache::Config.should_receive(:from_controller)
28
+ get('/', { :background_cache => key })
29
+ end
30
+
31
+ it "should alias read_fragment and return null when it is called on matching cache" do
32
+ key = BackgroundCache.set_key!
33
+ get('/', { :background_cache_load => key })
34
+ ::ActionController::Base.cache_store.write('views/test_3', 'bust me')
35
+ get('/t3', { :background_cache => key })
36
+ last_response.body.should == 'nil'
37
+ end
38
+ end
39
+
40
+ describe :cache! do
41
+
42
+ before(:each) do
43
+ ::ActionController::Base.cache_store.clear
44
+ end
45
+
46
+ describe :test_1 do
47
+
48
+ it "should be caching normally" do
49
+ get('/')
50
+ ::ActionController::Base.cache_store.read('views/test').should == 'test'
51
+ ::ActionController::Base.cache_store.write('views/test', 'bust me')
52
+ get('/')
53
+ ::ActionController::Base.cache_store.read('views/test').should == 'bust me'
54
+ end
55
+
56
+ it "should bust the cache" do
57
+ ::ActionController::Base.cache_store.write('views/test', 'bust me')
58
+ BackgroundCache.cache!
59
+ ::ActionController::Base.cache_store.read('views/test').gsub(COMMENT_REGEX, '').should == 'test'
60
+ end
61
+
62
+ it "should render the layout" do
63
+ BackgroundCache.cache!
64
+ ::ActionController::Base.cache_store.read('views/layout_test_1').gsub(COMMENT_REGEX, '').should == '1'
65
+ end
66
+ end
67
+
68
+ describe :test_2 do
69
+
70
+ it "should be caching normally" do
71
+ get('/t2')
72
+ ::ActionController::Base.cache_store.read('views/test_2').should == 'test 2'
73
+ ::ActionController::Base.cache_store.write('views/test_2', 'bust me')
74
+ get('/t2')
75
+ ::ActionController::Base.cache_store.read('views/test_2').should == 'bust me'
76
+ end
77
+
78
+ it "should bust the cache" do
79
+ ::ActionController::Base.cache_store.write('views/test_2', 'bust me')
80
+ BackgroundCache.cache!
81
+ ::ActionController::Base.cache_store.read('views/test_2').gsub(COMMENT_REGEX, '').should == 'test 2'
82
+ end
83
+
84
+ it "should not bust the excluded cache" do
85
+ ::ActionController::Base.cache_store.write('views/test_1', 'bust me')
86
+ BackgroundCache.cache!
87
+ ::ActionController::Base.cache_store.read('views/test_1').should == 'bust me'
88
+ end
89
+
90
+ it "should not render the layout" do
91
+ BackgroundCache.cache!
92
+ ::ActionController::Base.cache_store.read('views/layout_test_2').should == nil
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,14 @@
1
+ # Filters added to this controller apply to all controllers in the application.
2
+ # Likewise, all the methods added will be available for all controllers.
3
+
4
+ class ApplicationController < ActionController::Base
5
+ helper :all # include all helpers, all the time
6
+ protect_from_forgery # See ActionController::RequestForgeryProtection for details
7
+
8
+ # Scrub sensitive parameters from your log
9
+ # filter_parameter_logging :password
10
+
11
+ def test_3
12
+ render :text => read_fragment('test_3').inspect, :layout => false
13
+ end
14
+ end
@@ -0,0 +1,3 @@
1
+ # Methods added to this helper will be available to all templates in the application.
2
+ module ApplicationHelper
3
+ end
@@ -0,0 +1 @@
1
+ <% cache 'test' do -%>test<% end -%>
@@ -0,0 +1,2 @@
1
+ <% cache 'test_1' do -%>test<% end -%>
2
+ <% cache 'test_2' do -%>test 2<% end -%>
@@ -0,0 +1,4 @@
1
+ <html><body>
2
+ <% cache "layout_#{params[:action]}" do -%>1<% end -%>
3
+ <%= yield %>
4
+ </body></html>
@@ -0,0 +1,110 @@
1
+ # Don't change this file!
2
+ # Configure your app in config/environment.rb and config/environments/*.rb
3
+
4
+ RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
5
+
6
+ module Rails
7
+ class << self
8
+ def boot!
9
+ unless booted?
10
+ preinitialize
11
+ pick_boot.run
12
+ end
13
+ end
14
+
15
+ def booted?
16
+ defined? Rails::Initializer
17
+ end
18
+
19
+ def pick_boot
20
+ (vendor_rails? ? VendorBoot : GemBoot).new
21
+ end
22
+
23
+ def vendor_rails?
24
+ File.exist?("#{RAILS_ROOT}/vendor/rails")
25
+ end
26
+
27
+ def preinitialize
28
+ load(preinitializer_path) if File.exist?(preinitializer_path)
29
+ end
30
+
31
+ def preinitializer_path
32
+ "#{RAILS_ROOT}/config/preinitializer.rb"
33
+ end
34
+ end
35
+
36
+ class Boot
37
+ def run
38
+ load_initializer
39
+ Rails::Initializer.run(:set_load_path)
40
+ end
41
+ end
42
+
43
+ class VendorBoot < Boot
44
+ def load_initializer
45
+ require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
46
+ Rails::Initializer.run(:install_gem_spec_stubs)
47
+ Rails::GemDependency.add_frozen_gem_path
48
+ end
49
+ end
50
+
51
+ class GemBoot < Boot
52
+ def load_initializer
53
+ self.class.load_rubygems
54
+ load_rails_gem
55
+ require 'initializer'
56
+ end
57
+
58
+ def load_rails_gem
59
+ if version = self.class.gem_version
60
+ gem 'rails', version
61
+ else
62
+ gem 'rails'
63
+ end
64
+ rescue Gem::LoadError => load_error
65
+ $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
66
+ exit 1
67
+ end
68
+
69
+ class << self
70
+ def rubygems_version
71
+ Gem::RubyGemsVersion rescue nil
72
+ end
73
+
74
+ def gem_version
75
+ if defined? RAILS_GEM_VERSION
76
+ RAILS_GEM_VERSION
77
+ elsif ENV.include?('RAILS_GEM_VERSION')
78
+ ENV['RAILS_GEM_VERSION']
79
+ else
80
+ parse_gem_version(read_environment_rb)
81
+ end
82
+ end
83
+
84
+ def load_rubygems
85
+ min_version = '1.3.2'
86
+ require 'rubygems'
87
+ unless rubygems_version >= min_version
88
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
89
+ exit 1
90
+ end
91
+
92
+ rescue LoadError
93
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
94
+ exit 1
95
+ end
96
+
97
+ def parse_gem_version(text)
98
+ $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
99
+ end
100
+
101
+ private
102
+ def read_environment_rb
103
+ File.read("#{RAILS_ROOT}/config/environment.rb")
104
+ end
105
+ end
106
+ end
107
+ end
108
+
109
+ # All that for this:
110
+ Rails.boot!
@@ -0,0 +1,45 @@
1
+ # Be sure to restart your server when you modify this file
2
+
3
+ # Specifies gem version of Rails to use when vendor/rails is not present
4
+ RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
5
+
6
+ # Bootstrap the Rails environment, frameworks, and default configuration
7
+ require File.join(File.dirname(__FILE__), 'boot')
8
+
9
+ Rails::Initializer.run do |config|
10
+ # Settings in config/environments/* take precedence over those specified here.
11
+ # Application configuration should go into files in config/initializers
12
+ # -- all .rb files in that directory are automatically loaded.
13
+
14
+ # Add additional load paths for your own custom dirs
15
+ # config.load_paths += %W( #{RAILS_ROOT}/extras )
16
+
17
+ # Specify gems that this application depends on and have them installed with rake gems:install
18
+ # config.gem "bj"
19
+ # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
20
+ # config.gem "sqlite3-ruby", :lib => "sqlite3"
21
+ # config.gem "aws-s3", :lib => "aws/s3"
22
+
23
+ # Only load the plugins named here, in the order given (default is alphabetical).
24
+ # :all can be used as a placeholder for all plugins not explicitly named
25
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
26
+
27
+ # Skip frameworks you're not going to use. To use Rails without a database,
28
+ # you must remove the Active Record framework.
29
+ config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
30
+
31
+ # Activate observers that should always be running
32
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
33
+
34
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
35
+ # Run "rake -D time" for a list of tasks for finding time zone names.
36
+ config.time_zone = 'UTC'
37
+
38
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
39
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
40
+ # config.i18n.default_locale = :de
41
+
42
+ parent_dir = File.expand_path(File.dirname(__FILE__) + "/../../../../../")
43
+ config.plugin_paths = [ parent_dir ]
44
+ config.plugins = [ 'background_cache' ]
45
+ end
@@ -0,0 +1,17 @@
1
+ # Settings specified here will take precedence over those in config/environment.rb
2
+
3
+ # In the development environment your application's code is reloaded on
4
+ # every request. This slows down response time but is perfect for development
5
+ # since you don't have to restart the webserver when you make code changes.
6
+ config.cache_classes = false
7
+
8
+ # Log error messages when you accidentally call methods on nil.
9
+ config.whiny_nils = true
10
+
11
+ # Show full error reports and disable caching
12
+ config.action_controller.consider_all_requests_local = true
13
+ config.action_view.debug_rjs = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Don't care if the mailer can't send
17
+ config.action_mailer.raise_delivery_errors = false
@@ -0,0 +1,28 @@
1
+ # Settings specified here will take precedence over those in config/environment.rb
2
+
3
+ # The production environment is meant for finished, "live" apps.
4
+ # Code is not reloaded between requests
5
+ config.cache_classes = true
6
+
7
+ # Full error reports are disabled and caching is turned on
8
+ config.action_controller.consider_all_requests_local = false
9
+ config.action_controller.perform_caching = true
10
+ config.action_view.cache_template_loading = true
11
+
12
+ # See everything in the log (default is :info)
13
+ # config.log_level = :debug
14
+
15
+ # Use a different logger for distributed setups
16
+ # config.logger = SyslogLogger.new
17
+
18
+ # Use a different cache store in production
19
+ # config.cache_store = :mem_cache_store
20
+
21
+ # Enable serving of images, stylesheets, and javascripts from an asset server
22
+ # config.action_controller.asset_host = "http://assets.example.com"
23
+
24
+ # Disable delivery errors, bad email addresses will be ignored
25
+ # config.action_mailer.raise_delivery_errors = false
26
+
27
+ # Enable threaded mode
28
+ # config.threadsafe!
@@ -0,0 +1,28 @@
1
+ # Settings specified here will take precedence over those in config/environment.rb
2
+
3
+ # The test environment is used exclusively to run your application's
4
+ # test suite. You never need to work with it otherwise. Remember that
5
+ # your test database is "scratch space" for the test suite and is wiped
6
+ # and recreated between test runs. Don't rely on the data there!
7
+ config.cache_classes = true
8
+
9
+ # Log error messages when you accidentally call methods on nil.
10
+ config.whiny_nils = true
11
+
12
+ # Show full error reports and disable caching
13
+ config.action_controller.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+ config.action_view.cache_template_loading = true
16
+
17
+ # Disable request forgery protection in test environment
18
+ config.action_controller.allow_forgery_protection = false
19
+
20
+ # Tell Action Mailer not to deliver emails to the real world.
21
+ # The :test delivery method accumulates sent emails in the
22
+ # ActionMailer::Base.deliveries array.
23
+ config.action_mailer.delivery_method = :test
24
+
25
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
26
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
27
+ # like if you have constraints or database-specific column types
28
+ # config.active_record.schema_format = :sql
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4
+ # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5
+
6
+ # You can also remove all the silencers if you're trying do debug a problem that might steem from framework code.
7
+ # Rails.backtrace_cleaner.remove_silencers!
@@ -0,0 +1,10 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new inflection rules using the following format
4
+ # (all these examples are active by default):
5
+ # ActiveSupport::Inflector.inflections do |inflect|
6
+ # inflect.plural /^(ox)$/i, '\1en'
7
+ # inflect.singular /^(ox)en/i, '\1'
8
+ # inflect.irregular 'person', 'people'
9
+ # inflect.uncountable %w( fish sheep )
10
+ # end
@@ -0,0 +1,5 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new mime types for use in respond_to blocks:
4
+ # Mime::Type.register "text/richtext", :rtf
5
+ # Mime::Type.register_alias "text/html", :iphone
@@ -0,0 +1,21 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # These settings change the behavior of Rails 2 apps and will be defaults
4
+ # for Rails 3. You can remove this initializer when Rails 3 is released.
5
+
6
+ if defined?(ActiveRecord)
7
+ # Include Active Record class name as root for JSON serialized output.
8
+ ActiveRecord::Base.include_root_in_json = true
9
+
10
+ # Store the full class name (including module namespace) in STI type column.
11
+ ActiveRecord::Base.store_full_sti_class = true
12
+ end
13
+
14
+ ActionController::Routing.generate_best_match = false
15
+
16
+ # Use ISO 8601 format for JSON serialized times and dates.
17
+ ActiveSupport.use_standard_json_time_format = true
18
+
19
+ # Don't escape HTML entities in JSON, leave that for the #json_escape helper.
20
+ # if you're including raw json in an HTML page.
21
+ ActiveSupport.escape_html_entities_in_json = false
@@ -0,0 +1,15 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Your secret key for verifying cookie session data integrity.
4
+ # If you change this key, all old sessions will become invalid!
5
+ # Make sure the secret is at least 30 characters and all random,
6
+ # no regular words or you'll be exposed to dictionary attacks.
7
+ ActionController::Base.session = {
8
+ :key => '_rails_session',
9
+ :secret => '2d856fb7e64d38ed267dcfa20309b82d4d7d655d4182af025ab09b8e304620c4c7a23268ca349fa58e2de65aa33f67f38d005270b1f8ee9e5a56d7abfbda47d3'
10
+ }
11
+
12
+ # Use the database for sessions instead of the cookie-based default,
13
+ # which shouldn't be used to store highly confidential information
14
+ # (create the session table with "rake db:sessions:create")
15
+ # ActionController::Base.session_store = :active_record_store
@@ -0,0 +1,5 @@
1
+ # Sample localization file for English. Add more files in this directory for other locales.
2
+ # See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
3
+
4
+ en:
5
+ hello: "Hello world"
@@ -0,0 +1,48 @@
1
+ ActionController::Routing::Routes.draw do |map|
2
+ # The priority is based upon order of creation: first created -> highest priority.
3
+
4
+ # Sample of regular route:
5
+ # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
6
+ # Keep in mind you can assign values other than :controller and :action
7
+
8
+ # Sample of named route:
9
+ # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
10
+ # This route can be invoked with purchase_url(:id => product.id)
11
+
12
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
13
+ # map.resources :products
14
+
15
+ # Sample resource route with options:
16
+ # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
17
+
18
+ # Sample resource route with sub-resources:
19
+ # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
20
+
21
+ # Sample resource route with more complex sub-resources
22
+ # map.resources :products do |products|
23
+ # products.resources :comments
24
+ # products.resources :sales, :collection => { :recent => :get }
25
+ # end
26
+
27
+ # Sample resource route within a namespace:
28
+ # map.namespace :admin do |admin|
29
+ # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
30
+ # admin.resources :products
31
+ # end
32
+
33
+ # You can have the root of your site routed with map.root -- just remember to delete public/index.html.
34
+ # map.root :controller => "welcome"
35
+
36
+ # See how all your routes lay out with "rake routes"
37
+
38
+ # Install the default routes as the lowest priority.
39
+ # Note: These default routes make all actions in every controller accessible via GET requests. You should
40
+ # consider removing or commenting them out if you're using named routes and resources.
41
+
42
+ #map.connect ':controller/:action/:id'
43
+ #map.connect ':controller/:action/:id.:format'
44
+
45
+ map.connect '/', :controller => 'application', :action => 'test_1'
46
+ map.connect '/t2', :controller => 'application', :action => 'test_2'
47
+ map.connect '/t3', :controller => 'application', :action => 'test_3'
48
+ end
@@ -0,0 +1,15 @@
1
+ BackgroundCache::Config.new do |config|
2
+ config.cache(
3
+ :path => '/'
4
+ )
5
+ config.layout(false).only('test_2') do
6
+ config.cache(
7
+ :controller => 'application',
8
+ :action => 'test_2'
9
+ )
10
+ end
11
+ config.cache(
12
+ :controller => 'application',
13
+ :action => 'test_3'
14
+ )
15
+ end
@@ -0,0 +1,7 @@
1
+ RAILS_ENV = 'production'
2
+
3
+ require File.expand_path("#{File.dirname(__FILE__)}/../require")
4
+ Require.spec_helper!
5
+
6
+ Spec::Runner.configure do |config|
7
+ end
@@ -0,0 +1,4 @@
1
+ desc "Background cache cron job"
2
+ task :background_cache, :group, :needs => :environment do |t, args|
3
+ BackgroundCache.cache! args[:group]
4
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: background_cache
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Winton Welsh
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2010-06-08 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: rack-test
17
+ type: :runtime
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - "="
22
+ - !ruby/object:Gem::Version
23
+ version: 0.5.3
24
+ version:
25
+ - !ruby/object:Gem::Dependency
26
+ name: require
27
+ type: :runtime
28
+ version_requirement:
29
+ version_requirements: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "="
32
+ - !ruby/object:Gem::Version
33
+ version: 0.2.7
34
+ version:
35
+ description:
36
+ email: mail@wintoni.us
37
+ executables: []
38
+
39
+ extensions: []
40
+
41
+ extra_rdoc_files:
42
+ - README.markdown
43
+ files:
44
+ - init.rb
45
+ - lib/background_cache/config.rb
46
+ - lib/background_cache/controller.rb
47
+ - lib/background_cache/helper.rb
48
+ - lib/background_cache.rb
49
+ - MIT-LICENSE
50
+ - rails/init.rb
51
+ - Rakefile
52
+ - README.markdown
53
+ - require.rb
54
+ - spec/background_cache_spec.rb
55
+ - spec/fixtures/rails/app/controllers/application_controller.rb
56
+ - spec/fixtures/rails/app/helpers/application_helper.rb
57
+ - spec/fixtures/rails/app/views/application/test_1.html.erb
58
+ - spec/fixtures/rails/app/views/application/test_2.html.erb
59
+ - spec/fixtures/rails/app/views/layouts/application.html.erb
60
+ - spec/fixtures/rails/config/boot.rb
61
+ - spec/fixtures/rails/config/environment.rb
62
+ - spec/fixtures/rails/config/environments/development.rb
63
+ - spec/fixtures/rails/config/environments/production.rb
64
+ - spec/fixtures/rails/config/environments/test.rb
65
+ - spec/fixtures/rails/config/initializers/backtrace_silencers.rb
66
+ - spec/fixtures/rails/config/initializers/inflections.rb
67
+ - spec/fixtures/rails/config/initializers/mime_types.rb
68
+ - spec/fixtures/rails/config/initializers/new_rails_defaults.rb
69
+ - spec/fixtures/rails/config/initializers/session_store.rb
70
+ - spec/fixtures/rails/config/locales/en.yml
71
+ - spec/fixtures/rails/config/routes.rb
72
+ - spec/fixtures/rails/lib/background_cache_config.rb
73
+ - spec/spec_helper.rb
74
+ - tasks/background_cache.rake
75
+ has_rdoc: true
76
+ homepage: http://github.com/winton/background_cache
77
+ licenses: []
78
+
79
+ post_install_message:
80
+ rdoc_options: []
81
+
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: "0"
89
+ version:
90
+ required_rubygems_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: "0"
95
+ version:
96
+ requirements: []
97
+
98
+ rubyforge_project:
99
+ rubygems_version: 1.3.5
100
+ signing_key:
101
+ specification_version: 3
102
+ summary: Bust caches before your users do
103
+ test_files: []
104
+