Permalink
Browse files

MasterFilter instance mode and tests

  • Loading branch information...
1 parent a53ecbc commit 0385113df86bc22f40ab5d545dc4232e1e3196fa @mislav committed Apr 13, 2009
Showing with 79 additions and 4 deletions.
  1. +24 −4 lib/active_reload/master_filter.rb
  2. +55 −0 test/connection_proxy_test.rb
@@ -1,12 +1,32 @@
module ActiveReload
- # MasterFilter should be used as an around filter in your controllers that require certain actions to use the Master DB for reads as well as writes
+ # MasterFilter is an around filter for controllers that require certain actions
+ # to use the master database for both reads and writes
+ #
+ # Usage:
+ # # class level:
+ # around_filter ActiveReload::MasterFilter
+ #
+ # # instance level:
+ # around_filter ActiveReload::MasterFilter.new(MyModel)
class MasterFilter
def self.filter(controller, &block)
- if ActiveRecord::Base.connection.respond_to?(:with_master)
- ActiveRecord::Base.connection.with_master(&block)
+ with_master(&block)
+ end
+
+ def self.with_master(klass = ActiveRecord::Base)
+ if klass.connection.masochistic?
+ klass.connection.with_master { yield }
else
- yield block
+ yield
end
end
+
+ def initialize(klass)
+ @klass = klass
+ end
+
+ def filter(controller, &block)
+ self.class.with_master(@klass, &block)
+ end
end
end
@@ -4,6 +4,7 @@
require 'active_support/test_case'
require 'active_record'
require 'active_reload/connection_proxy'
+require 'active_reload/master_filter'
RAILS_ENV = 'test'
@@ -154,4 +155,58 @@ def test_transactions_run_on_master
end
assert_equal :slave, connection.current_type
end
+end
+
+class MasterFilterTest < MasochismTestCase
+ setup :prepare
+
+ def prepare
+ enable_masochism
+ @controller = mock
+ end
+
+ def test_yields_in_master_block
+ yielded = false
+ ActiveReload::MasterFilter.filter(@controller) do
+ assert_equal :master, connection.current_type
+ yielded = true
+ end
+ assert yielded
+ end
+
+ def test_doesnt_yield_in_master_without_masochism
+ connection.expects(:masochistic?).returns(false)
+
+ yielded = false
+ ActiveReload::MasterFilter.filter(@controller) do
+ assert_equal :slave, connection.current_type
+ yielded = true
+ end
+ assert yielded
+ end
+
+ def test_instance_mode
+ model = mock
+ model.stubs(:connection).returns(connection)
+
+ yielded = false
+ ActiveReload::MasterFilter.new(model).filter(@controller) do
+ assert_equal :master, connection.current_type
+ yielded = true
+ end
+ assert yielded
+ end
+
+ def test_instance_mode_without_masochism
+ model = mock
+ conn = mock
+ model.stubs(:connection).returns(conn)
+ conn.expects(:masochistic?).returns(false)
+
+ yielded = false
+ ActiveReload::MasterFilter.new(model).filter(@controller) do
+ yielded = true
+ end
+ assert yielded
+ end
end

0 comments on commit 0385113

Please sign in to comment.