即时用 link 替换子字符串
Replacing a substring with a link on the fly
在我的应用程序中,我存储电子邮件。
我想即时解析这些电子邮件以获取文本中的电子邮件地址,并将它们替换为 link(以便我们通过应用程序发送电子邮件)。
例如
@email.body = "Hi Tom, Drop me a line at jerry@cheese.com."
我需要某种帮手,可以将其即时翻译成:
@email.sanitized_body
"Hi Tom, Drop me a line at #{link_to "Email", email_send_email_path("jerry@cheese.com")}."
转了几圈。
例如在模型中
Class 邮箱
def sanitized_body
text = self.body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
emails.each do |email|
text.gsub!("jerry@cheese.com", helper.link_to("email", "http://www.google.com"))
end
text
end
我确定有一个明智的方法可以做到这一点,可能需要一个助手,但不能完全解决...
module EmailsHelper
def sanitized_body(email_body)
text = email_body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
emails.each do |email|
text.gsub!("jerry@cheese.com", "#{link_to("email", "http://www.google.com")}")
end
text
end
end
让我快到了。但是文本在显示时显示为字符串中的文本。
非常感谢任何帮助。
您应该使用 html_safe 让您的文本呈现为 HTML 代码而不是简单的字符串。
module EmailsHelper
def sanitized_body(email_body)
text = email_body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
replace_text = "You text %s" % helper.link_to("email", "http://www.google.com")
emails.each do |email|
text.gsub!("jerry@cheese.com", replace_text.html_safe)
end
text
end
end
在我的应用程序中,我存储电子邮件。
我想即时解析这些电子邮件以获取文本中的电子邮件地址,并将它们替换为 link(以便我们通过应用程序发送电子邮件)。
例如 @email.body = "Hi Tom, Drop me a line at jerry@cheese.com."
我需要某种帮手,可以将其即时翻译成:
@email.sanitized_body
"Hi Tom, Drop me a line at #{link_to "Email", email_send_email_path("jerry@cheese.com")}."
转了几圈。
例如在模型中
Class 邮箱
def sanitized_body
text = self.body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
emails.each do |email|
text.gsub!("jerry@cheese.com", helper.link_to("email", "http://www.google.com"))
end
text
end
我确定有一个明智的方法可以做到这一点,可能需要一个助手,但不能完全解决...
module EmailsHelper
def sanitized_body(email_body)
text = email_body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
emails.each do |email|
text.gsub!("jerry@cheese.com", "#{link_to("email", "http://www.google.com")}")
end
text
end
end
让我快到了。但是文本在显示时显示为字符串中的文本。
非常感谢任何帮助。
您应该使用 html_safe 让您的文本呈现为 HTML 代码而不是简单的字符串。
module EmailsHelper
def sanitized_body(email_body)
text = email_body
emails = text.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
replace_text = "You text %s" % helper.link_to("email", "http://www.google.com")
emails.each do |email|
text.gsub!("jerry@cheese.com", replace_text.html_safe)
end
text
end
end