简体   繁体   中英

Ruby on Rails 3 gsub escapes the anchor of link_to method

I want to check a string and change any @something to link. So I have a helper function which consists of something like this:

def parse(content)
  content.gsub(/@[a-zA-z0-9]+\b/, link_to("#{$1}", user_path($1)) )
end

But the result is <a href="/users/102"></a>

The problem is :

  1. The <a href="/users/102"></a> is a string, because somehow the < and > is escaped.
  2. Why does "#{$1}" return nothing? Isn't it supposed to return whatever is checked upon, in this case @something ?
  1. Rails HTML-escapes any content produced by a user-defined helper, unless you tell it not to. Try using <%= raw parse(content) %> in your view.
  2. Quoting Pickaxe on gsub :

If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, because substitution into the string occurs before the pattern match starts. However, the sequences \\1, \\2, and so on, may be used to interpolate successive numbered groups in the match, and \\k<name> will substitute the corresponding named captures.

So you can't use #{$1} because $1 isn't set until after the command has finished. Your best bet is probably to use the block form of gsub - in which case $1 is set inside the block. Try:

def parse(content)
  content.gsub(/@[a-zA-z0-9]+\b/) {link_to($1, user_path($1))} 
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM