Skip to content

Commit

Permalink
Escape regex-related characters in string literals.
Browse files Browse the repository at this point in the history
  • Loading branch information
jcoglan committed Jul 7, 2009
1 parent d98b239 commit 5156871
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
11 changes: 7 additions & 4 deletions lib/siren/json_query_nodes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -246,16 +246,19 @@ module Comparator
module Equal
def value(expr1, expr2)
return expr1 == expr2 unless expr2.respond_to?(:gsub)
expr2 = expr2.gsub('*', '.*').gsub('?', '.')
expr1 =~ %r{^#{expr2}$}
expr1 =~ %r{^#{Match.convert(expr2)}$}
end
end

module Match
def value(expr1, expr2)
return expr1 == expr2 unless expr2.respond_to?(:gsub)
expr2 = expr2.gsub('*', '.*').gsub('?', '.')
expr1 =~ %r{^#{expr2}$}i
expr1 =~ %r{^#{Match.convert(expr2)}$}i
end

def self.convert(string)
string.gsub(/([\.\+\[\]\{\}\(\)\^\$])/) { "\\#{$1}" }.
gsub('*', '.*').gsub('?', '.')
end
end

Expand Down
4 changes: 3 additions & 1 deletion test/test_siren.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def test_filters_with_cross_references
{:key => [9,5,7], :val => 1..8})
end

def test_wildcards
def test_string_matching
assert_equal ["Sayings of the Century", "The Lord of the Rings"],
Siren.query("$.store.book[? @.title = '* of the *'][= title]", fixtures(:store))

Expand All @@ -144,6 +144,8 @@ def test_wildcards

assert_equal [],
Siren.query("$.store.book[? @.title = '? of the ?'][= title]", fixtures(:store))

assert_equal '302 [QSA,L]', Siren.query("$[? @ = '302 [QSA,L]'][0]", ['302 [QSA,L]'])
end

def test_bookstore
Expand Down

0 comments on commit 5156871

Please sign in to comment.