Skip to content

Commit

Permalink
Screen blank array and hash params
Browse files Browse the repository at this point in the history
  • Loading branch information
tfwright committed Apr 24, 2013
1 parent 15d0679 commit 3fa4892
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/has_scope.rb
Expand Up @@ -115,6 +115,7 @@ def apply_scopes(target, hash=params)
end

value = parse_value(options[:type], key, value)
value = normalize_blanks(value)

if call_scope && (value.present? || options[:allow_blank])
current_scopes[key] = value
Expand All @@ -134,6 +135,18 @@ def parse_value(type, key, value) #:nodoc:
end
end

# Screens pseudo-blank params.
def normalize_blanks(value) #:nodoc:
return value if value.nil?
if value.is_a?(Array)
value.select { |v| v.present? }
elsif value.is_a?(Hash)
value.select { |k, v| normalize_blanks(v).present? }.with_indifferent_access
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]
Expand Down
35 changes: 35 additions & 0 deletions test/has_scope_test.rb
Expand Up @@ -161,6 +161,33 @@ 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_nested_hash_with_blank_values_is_ignored
hash = { "parent" => {"children" => ""} }
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_nested_blank_array_param_is_ignored
hash = { "parent" => [""] }
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)
Expand All @@ -170,6 +197,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"
Expand Down

0 comments on commit 3fa4892

Please sign in to comment.