Permalink
Browse files

using instance_exec to change scope of can blocks to instance of abil…

…ity, this is a bit ugly so I may end up using methods instead
  • Loading branch information...
1 parent be1892c commit c663effc06a4c6af00dc1530068849fde67030f3 @ryanb committed Nov 17, 2009
Showing with 32 additions and 1 deletion.
  1. +1 −0 lib/cancan.rb
  2. +9 −1 lib/cancan/ability.rb
  3. +15 −0 lib/cancan/instance_exec.rb
  4. +7 −0 spec/cancan/ability_spec.rb
View
@@ -1,2 +1,3 @@
$:.unshift(File.dirname(__FILE__))
require 'cancan/ability'
+require 'cancan/instance_exec'
View
@@ -1,5 +1,7 @@
module CanCan
module Ability
+ attr_accessor :user
+
def self.included(base)
base.extend ClassMethods
base.alias_action :index, :show, :to => :read
@@ -18,7 +20,7 @@ def can?(original_action, target)
block_args << action if can_action == :manage
block_args << (target.class == Class ? target : target.class) if can_target == :all
block_args << (target.class == Class ? nil : target)
- return can_block.call(*block_args)
+ return instance_exec(*block_args, &can_block)
end
end
end
@@ -48,6 +50,12 @@ def alias_action(*args)
target = args.pop[:to]
@aliased_actions[target] = args
end
+
+ def for_user(user)
+ ability = new
+ ability.user = user
+ ability
+ end
end
end
end
@@ -0,0 +1,15 @@
+# see http://eigenclass.org/hiki.rb?instance_exec
+class Object
+ module InstanceExecHelper; end
+ include InstanceExecHelper
+ def instance_exec(*args, &block) # !> method redefined; discarding old instance_exec
+ mname = "__instance_exec_#{Thread.current.object_id.abs}_#{object_id.abs}"
+ InstanceExecHelper.module_eval{ define_method(mname, &block) }
+ begin
+ ret = send(mname, *args)
+ ensure
+ InstanceExecHelper.module_eval{ undef_method(mname) } rescue nil
+ end
+ ret
+ end
+end
@@ -77,4 +77,11 @@
@ability.can?(:new, 123).should == :create_called
@ability.can?(:edit, 123).should == :update_called
end
+
+ it "should be able to access given user" do
+ @ability_class.can(:preview, :all) { user }
+ ability = @ability_class.for_user(:some_user)
+ ability.user.should == :some_user
+ ability.can?(:preview, 123).should == :some_user
+ end
end

0 comments on commit c663eff

Please sign in to comment.