Rails: using gsub to find and make links -


i've got text area called body in model. i'd change every image link image. i've got method supposed doesn't seem work. breaks @ each image.

def get_images_in(body)   body_with_links = body.gsub( %r{http://[^\s<]+} ) |url|     if url[/(?:png|jpe?g|gif|svg)$/]       "<a href='#{url}' target='_blank'><img src='#{url}' /></a>"     end   end   return body_with_links end 

any ideas? thank-you!

update

here's link gist sample body text.

first things first, don't need use return statement in ruby. ruby return last thing default. in case, string returned gsub:

def wrap_image_with_link(body)   body.gsub( %r{http://[^\s<]+} ) |url|     if url[/(?:png|jpe?g|gif|svg)$/]       "<a href='#{url}' target='_blank'><img src='#{url}' /></a>"     end   end end 

this still isn't quite right. focus initial regular expression on img tag:

def wrap_image_with_link(body)   body.gsub(/\<img.*src\=['"](.*)['"].*\/\>/) |url|     "<a href='#{url}' target='_blank'><img src='#{url}' /></a>"   end end 

rails has couple helpers clean up.

def wrap_images_with_links(body)   body.gsub(/\<img.*src\=['"](.*)['"].*\/\>/)         link_to(image_tag($1), $1, :target => '_blank')   end end 

you want make reg ex case insensitive:

def wrap_images_with_links(body)   body.gsub(/.*\<img.*src\=['"](.*)['"].*\/\>/i)         link_to(image_tag($1), $1, :target => '_blank')   end end 

so gsub, opposed sub, changes every instance of matched reg-ex, need tweak reg ex accommodate more explicit matches:

def wrap_images_with_links(body)   body.gsub(/\<img[\s\w"=]+src\=['"](http[s]?:\/\/[\w.\/]+)['"]\s?[\/]?\>/i)         link_to(image_tag($1), $1, :target => '_blank')   end end 

depending on complexities of urls, might need tweak reg-ex support ? or characters other white space, work pretty well.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -