Permalink
Browse files

Screen blank array and hash params

  • Loading branch information...
1 parent 15d0679 commit 52a6442772ed385af069cdfe7e67cc668b24384d @tfwright committed Feb 8, 2013
Showing with 30 additions and 1 deletion.
  1. +13 −1 lib/has_scope.rb
  2. +17 −0 test/has_scope_test.rb
View
@@ -115,6 +115,7 @@ def apply_scopes(target, hash=params)
end
value = parse_value(options[:type], key, value)
+ value = normalize_blanks(options[:type], value) if value
if call_scope && (value.present? || options[:allow_blank])
current_scopes[key] = value
@@ -134,14 +135,25 @@ def parse_value(type, key, value) #:nodoc:
end
end
+ # Screens pseudo-blank params.
+ def normalize_blanks(type, value) #:nodoc:
+ if type == :array
+ value.select { |v| v.present? }
+ elsif type == :hash
+ value.select { |k, v| v.present? }
+ else
+ value
+ end
+ end
+
# Call the scope taking into account its type.
def call_scope_by_type(type, scope, target, value, options) #:nodoc:
block = options[:block]
if type == :boolean
block ? block.call(self, target) : target.send(scope)
elsif value && options.key?(:using)
- value = value.values_at(*options[:using])
+ value = value.values_at(*options[:using].map(&:to_s))
block ? block.call(self, target, value) : target.send(scope, *value)
else
block ? block.call(self, target, value) : target.send(scope, value)
@@ -161,6 +161,15 @@ def test_scope_of_type_hash_with_using
assert_equal({ :args_paginate => hash }, current_scopes)
end
+ def test_hash_with_blank_values_is_ignored
+ hash = { "page" => "", "per_page" => "" }
+ Tree.expects(:paginate).never
+ Tree.expects(:all).returns([mock_tree])
+ get :index, :paginate => hash
+ assert_equal([mock_tree], assigns(:trees))
+ assert_equal({ }, current_scopes)
+ end
+
def test_scope_of_type_array
array = %w(book kitchen sport)
Tree.expects(:categories).with(array).returns(Tree)
@@ -170,6 +179,14 @@ def test_scope_of_type_array
assert_equal({ :categories => array }, current_scopes)
end
+ def test_array_of_blank_values_is_ignored
+ Tree.expects(:categories).never
+ Tree.expects(:all).returns([mock_tree])
+ get :index, :categories => [""]
+ assert_equal([mock_tree], assigns(:trees))
+ assert_equal({ }, current_scopes)
+ end
+
def test_scope_of_invalid_type_silently_fails
Tree.expects(:all).returns([mock_tree])
get :index, :paginate => "1"

0 comments on commit 52a6442

Please sign in to comment.