[PATCH] preload_app can take an optional block for warmup

Aman Gupta aman at tmm1.net
Fri Sep 20 21:40:56 UTC 2013


---
 lib/unicorn/configurator.rb    | 19 ++++++++++++++++---
 lib/unicorn/http_server.rb     |  3 +++
 test/unit/test_configurator.rb |  8 ++++++++
 3 files changed, 27 insertions(+), 3 deletions(-)

diff --git a/lib/unicorn/configurator.rb b/lib/unicorn/configurator.rb
index 0d0eac7..a0ae576 100644
--- a/lib/unicorn/configurator.rb
+++ b/lib/unicorn/configurator.rb
@@ -441,9 +441,22 @@ class Unicorn::Configurator
   # by properly deploying all required code and dependencies.
   # Using preload_app=true means any application load error will
   # cause the master process to exit with an error.
-
-  def preload_app(bool)
-    set_bool(:preload_app, bool)
+  #
+  # preload_app can also take an optional block. This block will be invoked
+  # with the rack application and can be used to "warm up" the application
+  # before deployment:
+  #
+  #  preload_app do |app|
+  #    client = Rack::MockRequest.new(app)
+  #    client.get('/')
+  #  end
+  #
+  def preload_app(bool=nil, &block)
+    if block_given? || bool.respond_to?(:call)
+      set_hook(:preload_app, block_given? ? block : bool, 1)
+    else
+      set_bool(:preload_app, bool)
+    end
   end
 
   # Toggles making \env[\"rack.input\"] rewindable.
diff --git a/lib/unicorn/http_server.rb b/lib/unicorn/http_server.rb
index bed24d0..d749a92 100644
--- a/lib/unicorn/http_server.rb
+++ b/lib/unicorn/http_server.rb
@@ -721,6 +721,9 @@ class Unicorn::HttpServer
         Gem.refresh
       end
       self.app = app.call
+      if preload_app.respond_to?(:call)
+        preload_app[app]
+      end
     end
   end
 
diff --git a/test/unit/test_configurator.rb b/test/unit/test_configurator.rb
index 1298f0e..8a1a68e 100644
--- a/test/unit/test_configurator.rb
+++ b/test/unit/test_configurator.rb
@@ -172,4 +172,12 @@ class TestConfigurator < Test::Unit::TestCase
     end
   end
 
+  def test_preload_app
+    test_struct = TestStruct.new
+    [ true, false, proc { |a| }, Proc.new { |a| }, lambda { |a| } ].each do |my_proc|
+      Unicorn::Configurator.new(:preload_app => my_proc).commit!(test_struct)
+      assert_equal my_proc, test_struct.preload_app
+    end
+  end
+
 end
-- 
1.8.3.4



More information about the mongrel-unicorn mailing list