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 :
<a href="/users/102"></a>
is a string, because somehow the <
and >
is escaped. "#{$1}"
return nothing? Isn't it supposed to return whatever is checked upon, in this case @something
? <%= raw parse(content) %>
in your view. 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.