开发者

How do you store a Ruby regex via a Rails controller?

For an admin function in a Rails app, I want to be able to store regexes in the DB (as strings), and add them via a standard controller action.

I've run into 2 issues:

1) The Rails parameter filters seem to be automatically escaping backslashes (escape characters), which messes up the regex. For instance:

\s{1,2}(foo)

becomes:

\\s{1,2}(foo)

2) So then I tried to use a write_attribute to gsub instances of double backslashes with single backslashes (essentially unescaping them). This proved to be much trickier than expected. (I'm using Ruby 1.9.2 if it matters). Some things I've found:

"hello\\world".gsub(/\\/, ' ') #=>开发者_开发技巧 "hello world"
"hello\\world".gsub(/\\/, "\\") #=> "hello\\world"
"hello\\world".gsub(/\\/, '\\') #=> "hello\\world"

What I'm trying to do is:

"hello\\world".gsub(/\\/, something) #=> "hello\world"

I'd love to know both solutions.

1) How can you safely pass and store regexes as params to a Rails controller action?

2) How can you substitute double backslashes with a single backslash?


In short, you can't substitute a double backslash with a single one in a string, because a single backslash in a string is an escape character. What you can do is the following:

Regexp.new("hello\\world") #=> /hello\world/

This will convert your string into a regular expression. So that means: store your regular expressions as strings (with the escaped characters) and convert them into regular expressions when you want to compare against them:

regexp = "\\s{1,2}(foo)"
reg = Regexp.new(regexp) #=> /\s{1,2}(foo)/
" foo" =~ reg #=> 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜