From a157b65fbf4122bea3433d132f89090a9ef7e31c Mon Sep 17 00:00:00 2001 From: Ryan Bates Date: Fri, 6 Aug 2010 09:35:07 -0700 Subject: [PATCH] adding :instance_name option to load/authorize_resource - closes #44 --- lib/cancan/controller_resource.rb | 8 ++++++-- spec/cancan/controller_resource_spec.rb | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/cancan/controller_resource.rb b/lib/cancan/controller_resource.rb index 39502cd..1b8a337 100644 --- a/lib/cancan/controller_resource.rb +++ b/lib/cancan/controller_resource.rb @@ -25,7 +25,7 @@ module CanCan def load_resource if !resource_instance && (parent? || member_action?) - @controller.instance_variable_set("@#{name}", load_resource_instance) + @controller.instance_variable_set("@#{instance_name}", load_resource_instance) end end @@ -72,7 +72,7 @@ module CanCan end def resource_instance - @controller.instance_variable_get("@#{name}") + @controller.instance_variable_get("@#{instance_name}") end # The object that methods (such as "find", "new" or "build") are called on. @@ -94,6 +94,10 @@ module CanCan @params[:controller].sub("Controller", "").underscore.split('/').last.singularize end + def instance_name + @options[:instance_name] || name + end + def collection_actions [:index] + [@options[:collection]].flatten end diff --git a/spec/cancan/controller_resource_spec.rb b/spec/cancan/controller_resource_spec.rb index 1fd670c..6ea5895 100644 --- a/spec/cancan/controller_resource_spec.rb +++ b/spec/cancan/controller_resource_spec.rb @@ -179,6 +179,15 @@ describe CanCan::ControllerResource do lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied) end + it "should load and authorize using custom instance name" do + @params.merge!(:action => "show", :id => 123) + stub(Ability).find(123) { :some_ability } + stub(@controller).authorize!(:show, :some_ability) { raise CanCan::AccessDenied } + resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_ability) + lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied) + @controller.instance_variable_get(:@custom_ability).should == :some_ability + end + it "should raise ImplementationRemoved when adding :name option" do lambda { CanCan::ControllerResource.new(@controller, :name => :foo)