본문 바로가기

Ruby on Rails

문자열 내에 링크가 있으면 <a href> 구문을 추가해주는 헬퍼

def convert_link_in_string( string )
regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"

content = string

if string.match( regex ).present? && string.match( regex )[0].present? && string.match( regex )[0].include?('http')
link = string.match( regex )[0]
content = string.gsub(link, "<a href=#{ link } target='_blank'>#{ link }</a>")
end

return raw( content )
end