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 Feb 8, 2013
1 parent 15d0679 commit 52a6442
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/has_scope.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions test/has_scope_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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"
Expand Down

0 comments on commit 52a6442

Please sign in to comment.