diff --git a/CHANGELOG b/CHANGELOG index 0606dafb..5561c452 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ # Version 0.7 +* Allow procs as default value in has scope to be able to use values from session, for example. * Allow blocks with arity 0 or -1 to be given as the redirect url: def destroy diff --git a/README b/README index b0139032..b5c54c72 100644 --- a/README +++ b/README @@ -309,7 +309,7 @@ it also is named_scope fluent. Let's suppose our Project model with the scopes: Your controller: - class GraduationsController < InheritedResources::Base + class ProjectsController < InheritedResources::Base has_scope :featured, :boolean => true, :only => :index has_scope :by_methodology has_scope :limit, :default => 10 @@ -331,6 +331,11 @@ In the last case, it would return: { :featured => "true", :by_methodology => "agile", :limit => "20" } +Finally, let's suppose you store on the session how many projects the user sees +per page. In such cases, you can give a proc as default value: + + has_scope :limit, :default => proc{|c| c.session[:limit] || 10 } + Belongs to ---------- diff --git a/lib/inherited_resources/has_scope_helpers.rb b/lib/inherited_resources/has_scope_helpers.rb index f64dc38e..7de4c57b 100644 --- a/lib/inherited_resources/has_scope_helpers.rb +++ b/lib/inherited_resources/has_scope_helpers.rb @@ -23,6 +23,7 @@ def apply_scope_to(target_object) #:nodoc: value, call_scope = params[key], true elsif options.key?(:default) value, call_scope = options[:default], true + value = value.call(self) if value.is_a?(Proc) end if call_scope diff --git a/test/has_scope_test.rb b/test/has_scope_test.rb index a68e140c..16c48d6e 100644 --- a/test/has_scope_test.rb +++ b/test/has_scope_test.rb @@ -7,8 +7,9 @@ def self.human_name; 'Tree'; end class TreesController < InheritedResources::Base has_scope :color has_scope :only_tall, :boolean => true, :only => :index - has_scope :shadown_range, :default => 10, :except => [ :index, :show, :destroy ] + has_scope :shadown_range, :default => 10, :except => [ :index, :show, :destroy, :new ] has_scope :root_type, :key => :root + has_scope :calculate_height, :default => proc {|c| c.session[:height] || 20 }, :only => :new end class HasScopeTest < ActionController::TestCase @@ -92,6 +93,15 @@ def test_scope_with_different_key assert_equal({ :root => 'outside' }, assigns(:current_scopes)) end + def test_scope_with_default_value_as_proc + session[:height] = 100 + Tree.expects(:calculate_height).with(100).returns(Tree).in_sequence + Tree.expects(:new).returns(mock_tree).in_sequence + get :new + assert_equal(mock_tree, assigns(:tree)) + assert_equal({ :calculate_height => 100 }, assigns(:current_scopes)) + end + protected def mock_tree(stubs={})