views:

253

answers:

3
+1  Q: 

Ruby gsub function

Hello

I'm trying to create a BBcode [code] tag for my rails forum, and I have a problem with the expression:

param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>\1</pre>' )

How do I get what the regex match returns (the text inbetween the [code][/code] tags), and escape all the html and some other characters in it?

I've tried this:

param_string.gsub!( /\[code\](.*?)\[\/code\]/im, '<pre>' + my_escape_function('\1') + '</pre>' )

but it didn't work. It just passes "\1" as a string to the function.

A: 

Someone here posted an answer, but they've deleted it.

I've tried their suggestion, and made it work with a small change. Whoever you are, thanks! :)

Here it is

param_string.gsub!( /\[code\](.*?)\[\/code\]/im ) {|s| '<pre>' + my_escape_function(s) + '</pre>' }
Marjan
A: 

You can simply use "<pre>#{$1}</pre>" for your replacement value.

gabriel
A: 

you should take care about the greedy behavior of the regular expressions, so the correct code looks like this:

html.gsub!(/\[(\S*?)\](.*?)\[\/\1\]/) { |m| escape_method($1, $2) }

the escape_method then looks like this:

def escape_method( type, string )
  case type.downcase.to_sym
    when :code
      "<pre>#{string}</pre>"
    when :bold
      "<b>#{string}</b>"
    else
       string
  end
end
KARASZI István
as you can see this code can be extended to support every BBcode tag
KARASZI István
That's a great advice, should speed things up a lot. Thanks!
Marjan