views:

69

answers:

2

I have a database full of text fields that look like this:

(paragraph of normal text)

image:blog/clownboy.jpg

(another paragraph)

I'm trying to write a view helper for Rails that will take one of these big blocks of text, find bits like "image:blog/clownboy.jpg" and replace them with the corresponding <img src="blog/clownboy.jpg"> (without disturbing the surrounding whitespace) before outputting it to the user. I've been trying for an hour or so now, but I'm new to Ruby and the regular expressions are still a bit beyond me.

+3  A: 

Global substitution of image: xyz on a separate line with <img src='xyz'/>:

text.gsub!(/^image:(.+)$/) { "<img src='#{$1}'/>" }
Magnar
This is really close, but it doesn't seem to handle the surrounding whitespace properly. If my text field contains "\r\n\r\nimage:foobar.jpg\r\n\r\n" then this approach gives me "\r\n\r\n<img src='foobar.jpg\r'/>\n\r\n", which isn't a proper link. I'm playing with the regex, but I'm not sure what to use instead of the "(.+)$"
David Tildon
change the regex to: /^image:(\S+)/
amikazmi
That did it! Thanks!
David Tildon
A: 

What database are you using? You might want to do this replacement on the query level ...

The REPLACE function would work, you can use that in MySQL, SQL Server, etc.

SELECT REPLACE('abcdefghicde','cde','xxx');

http://www.electrictoolbox.com/mysql-select-replace/

http://msdn.microsoft.com/en-us/library/ms186862.aspx

Justin Jenkins