Skip to content

Commit

Permalink
Allow procs to be given as default values to has scope.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Apr 28, 2009
1 parent 3b41204 commit e094deb
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions 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
Expand Down
7 changes: 6 additions & 1 deletion README
Expand Up @@ -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
Expand All @@ -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
----------

Expand Down
1 change: 1 addition & 0 deletions lib/inherited_resources/has_scope_helpers.rb
Expand Up @@ -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
Expand Down
12 changes: 11 additions & 1 deletion test/has_scope_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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={})
Expand Down

0 comments on commit e094deb

Please sign in to comment.