diff options
-rw-r--r-- | activerecord/lib/active_record/sanitization.rb | 3 | ||||
-rw-r--r-- | activerecord/test/cases/sanitize_test.rb | 9 |
2 files changed, 7 insertions, 5 deletions
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index ef63949208..be62e41932 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -110,7 +110,8 @@ module ActiveRecord # Sanitizes a +string+ so that it is safe to use within a sql # LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%" def sanitize_sql_like(string, escape_character = "\\") - string.gsub(/[\\_%]/) { |x| [escape_character, x].join } + pattern = Regexp.union(escape_character, "%", "_") + string.gsub(pattern) { |x| [escape_character, x].join } end # Accepts an array of conditions. The array has each value diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index 18182efc46..c7cc214c3f 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -62,19 +62,20 @@ class SanitizeTest < ActiveRecord::TestCase def test_sanitize_sql_like_with_custom_escape_character assert_equal '100!%', Binary.send(:sanitize_sql_like, '100%', '!') assert_equal 'snake!_cased!_string', Binary.send(:sanitize_sql_like, 'snake_cased_string', '!') - assert_equal 'C:!\\Programs!\\MsPaint', Binary.send(:sanitize_sql_like, 'C:\\Programs\\MsPaint', '!') + assert_equal 'great!!', Binary.send(:sanitize_sql_like, 'great!', '!') + assert_equal 'C:\\Programs\\MsPaint', Binary.send(:sanitize_sql_like, 'C:\\Programs\\MsPaint', '!') assert_equal 'normal string 42', Binary.send(:sanitize_sql_like, 'normal string 42', '!') end def test_sanitize_sql_like_example_use_case searchable_post = Class.new(Post) do def self.search(term) - where("title LIKE ?", sanitize_sql_like(term)) + where("title LIKE ?", sanitize_sql_like(term, '!')) end end - assert_sql /LIKE '20\\% \\_reduction\\_'/ do - searchable_post.search("20% _reduction_").to_a + assert_sql /LIKE '20!% !_reduction!_!!'/ do + searchable_post.search("20% _reduction_!").to_a end end end |