From 53ef01b9e69234e1f406030f0cfc9404957c9c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kevin=20Sj=C3=B6berg?= Date: Wed, 6 Feb 2013 11:26:06 +0100 Subject: [PATCH] Fix issue #190 and #195 This resolves issues where an integer column would raise an exception when handled by Ransack::Constants.escape_wildcards. --- lib/ransack/constants.rb | 2 +- spec/ransack/predicate_spec.rb | 23 +++++++++++++++++++---- spec/spec_helper.rb | 2 ++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/lib/ransack/constants.rb b/lib/ransack/constants.rb index 5b5908e..01eb3b2 100644 --- a/lib/ransack/constants.rb +++ b/lib/ransack/constants.rb @@ -23,7 +23,7 @@ module Ransack module_function # replace % \ to \% \\ def escape_wildcards(unescaped) - unescaped.gsub(/([\\|\%|.])/, '\\\\\\1') + unescaped.to_s.gsub(/([\\|\%|.])/, '\\\\\\1') end end end diff --git a/spec/ransack/predicate_spec.rb b/spec/ransack/predicate_spec.rb index 4d67917..aae41d7 100644 --- a/spec/ransack/predicate_spec.rb +++ b/spec/ransack/predicate_spec.rb @@ -7,6 +7,17 @@ module Ransack @s = Search.new(Person) end + shared_examples 'wildcard escaping' do |method, regexp| + it 'automatically converts integers to strings' do + subject.parent_id_cont = 1 + expect { subject.result }.to_not raise_error + end + it "escapes '%', '.' and '\\\\' in value" do + subject.public_send(:"#{method}=", '%._\\') + subject.result.to_sql.should match(regexp) + end + end + describe 'eq' do it 'generates an equality condition for boolean true' do @s.awesome_eq = true @@ -25,17 +36,21 @@ module Ransack end describe 'cont' do + it_has_behavior 'wildcard escaping', :name_cont, /"people"."name" LIKE '%\\%\\._\\\\%'/ do + subject { @s } + end + it 'generates a LIKE query with value surrounded by %' do @s.name_cont = 'ric' @s.result.to_sql.should match /"people"."name" LIKE '%ric%'/ end - it 'escapes %, . and \\ in value' do - @s.name_cont = '%._\\' - @s.result.to_sql.should match /"people"."name" LIKE '%\\%\\._\\\\%'/ - end end describe 'not_cont' do + it_has_behavior 'wildcard escaping', :name_not_cont, /"people"."name" NOT LIKE '%\\%\\._\\\\%'/ do + subject { @s } + end + it 'generates a NOT LIKE query with value surrounded by %' do @s.name_not_cont = 'ric' @s.result.to_sql.should match /"people"."name" NOT LIKE '%ric%'/ diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6cf14bd..52a97d1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -20,6 +20,8 @@ Sham.define do end RSpec.configure do |config| + config.alias_it_behaves_like_to :it_has_behavior, 'has behavior' + config.before(:suite) do puts '=' * 80 puts "Running specs against ActiveRecord #{ActiveRecord::VERSION::STRING} and ARel #{Arel::VERSION}..."