Skip to content

Commit

Permalink
Add ability to pass boolean scope args in array
Browse files Browse the repository at this point in the history
  • Loading branch information
shekibobo committed Oct 31, 2014
1 parent 314e28f commit e38edb9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
10 changes: 7 additions & 3 deletions lib/ransack/search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,16 @@ def add_scope(key, args)
if @context.scope_arity(key) == 1
@scope_args[key] = args.is_a?(Array) ? args[0] : args
else
@scope_args[key] = args
@scope_args[key] = args.is_a?(Array) ? sanitized_scope_args(args) : args
end
@context.chain_scope(key, scope_args(args))
@context.chain_scope(key, sanitized_scope_args(args))
end

def scope_args(args)
def sanitized_scope_args(args)
if args.is_a?(Array)
args = args.map(&method(:sanitized_scope_args))
end

if Ransack::Constants::TRUE_VALUES.include? args
true
elsif Ransack::Constants::FALSE_VALUES.include? args
Expand Down
12 changes: 11 additions & 1 deletion spec/ransack/adapters/active_record/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ module ActiveRecord

context 'with scopes' do
before do
Person.stub :ransackable_scopes => [:active, :over_age]
Person.stub :ransackable_scopes => [:active, :over_age, :of_age]
end

it "applies true scopes" do
Expand All @@ -33,6 +33,16 @@ module ActiveRecord
search.result.to_sql.should include "active = 1"
end

it "applies stringy boolean scopes with true value in an array" do
search = Person.search('of_age' => ['true'])
search.result.to_sql.should include "age >= 18"
end

it "applies stringy boolean scopes with false value in an array" do
search = Person.search('of_age' => ['false'])
search.result.to_sql.should include "age < 18"
end

it "ignores unlisted scopes" do
search = Person.search('restricted' => true)
search.result.to_sql.should_not include "restricted"
Expand Down
1 change: 1 addition & 0 deletions spec/support/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class Person < ActiveRecord::Base
scope :restricted, lambda { where("restricted = 1") }
scope :active, lambda { where("active = 1") }
scope :over_age, lambda { |y| where(["age > ?", y]) }
scope :of_age, lambda { |of_age| of_age ? where("age >= ?", 18) : where("age < ?", 18) }

ransacker :reversed_name, :formatter => proc { |v| v.reverse } do |parent|
parent.table[:name]
Expand Down

0 comments on commit e38edb9

Please sign in to comment.