Skip to content

Commit

Permalink
Added with_scope method and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronrenner committed Aug 31, 2012
1 parent 9237669 commit 4888291
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/acts_as_tenant/model_extensions.rb
Expand Up @@ -6,6 +6,20 @@ module ActsAsTenant
class << self
cattr_accessor :tenant_class
attr_accessor :current_tenant

# Sets the current_tenant within the given block
def with_tenant(tenant, &block)
if block.nil?
raise ArgumentError, "block required"
end

old_tenant = self.current_tenant
self.current_tenant = tenant

block.call

self.current_tenant= old_tenant
end
end

module ModelExtensions
Expand Down
27 changes: 27 additions & 0 deletions spec/model_extensions_spec.rb
Expand Up @@ -220,4 +220,31 @@ class SubTask < ActiveRecord::Base
ActsAsTenant.current_tenant = @account
Task.create(:name => 'bar').valid?.should == true
end

describe "::with_tenant" do
it "should set current_tenant to the specified tenant inside the block" do
@account = Account.create!(:name => 'baz')

ActsAsTenant.with_tenant(@account) do
ActsAsTenant.current_tenant.should eq(@account)
end
end


it "should return current_tenant to the previous tenant once exiting the block" do
@account1 = Account.create!(:name => 'foo')
@account2 = Account.create!(:name => 'bar')

ActsAsTenant.current_tenant = @account1
ActsAsTenant.with_tenant @account2 do

end

ActsAsTenant.current_tenant.should eq(@account1)
end

it "should raise an error when no block is provided" do
expect { ActsAsTenant.with_tenant(nil) }.to raise_error(ArgumentError, /block required/)
end
end
end

0 comments on commit 4888291

Please sign in to comment.