Allow adding of custom predicates that take arrays (like IN/NOT IN)

This commit is contained in:
Asfand Qazi 2012-05-02 07:54:12 +01:00
parent e69031b78a
commit afdd357fae
4 changed files with 26 additions and 1 deletions

View File

@ -19,6 +19,7 @@ module Ransack
opts[:name] = name
compounds = opts.delete(:compounds)
compounds = true if compounds.nil?
compounds = false if opts[:wants_array]
opts[:arel_predicate] = opts[:arel_predicate].to_s
self.predicates[name] = Predicate.new(opts)

View File

@ -41,7 +41,7 @@ module Ransack
@formatter = opts[:formatter]
@validator = opts[:validator] || lambda { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
@compound = opts[:compound]
@wants_array = @compound || ['in', 'not_in'].include?(@arel_predicate)
@wants_array = opts[:wants_array] == true || @compound || ['in', 'not_in'].include?(@arel_predicate)
end
def eql?(other)

View File

@ -45,5 +45,15 @@ module Ransack
# restore original state so we don't break other tests
Ransack.options = before
end
it 'adds predicates that take arrays, overriding compounds' do
Ransack.configure do |config|
config.add_predicate :test_array_predicate, :wants_array => true, :compounds => true
end
Ransack.predicates['test_array_predicate'].wants_array.should eq true
Ransack.predicates.should_not have_key 'test_array_predicate_any'
Ransack.predicates.should_not have_key 'test_array_predicate_all'
end
end
end

View File

@ -90,6 +90,20 @@ module Ransack
conditions.should have(2).items
conditions.map {|c| c.class}.should eq [Nodes::Condition, Nodes::Condition]
end
it 'creates Conditions for custom predicates that take arrays' do
Ransack.configure do |config|
config.add_predicate 'ary_pred',
:wants_array => true
end
search = Search.new(Person, :name_ary_pred => ['Ernie', 'Bert'])
condition = search.base[:name_ary_pred]
condition.should be_a Nodes::Condition
condition.predicate.name.should eq 'ary_pred'
condition.attributes.first.name.should eq 'name'
condition.value.should eq ['Ernie', 'Bert']
end
end
describe '#result' do