【问题标题】:Replacing a substring with a link on the fly即时用链接替换子字符串
【发布时间】:2015-09-10 17:04:43
【问题描述】:

在我的应用程序中,我存储电子邮件。

我想动态解析这些电子邮件以获取文本中的电子邮件地址,并用链接替换它们(以便我们通过应用程序发送电子邮件)。

例如 @email.body = "嗨,汤姆,给我写信到 jerry@cheese.com。"

我想要某种帮手,可以即时将其翻译成:

@email.sanitized_body

“嗨,Tom,请在 #{link_to "Email", email_send_email_path("jerry@cheese.com")} 给我留言。”

我已经绕了几个圈子。 例如在模型中
班级邮箱

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

让我快到了。但是文本在显示时会作为字符串中的文本出现。

非常感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails hyperlink


    【解决方案1】:

    您应该使用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
    

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 2012-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2014-06-09
      • 2019-04-15
      相关资源
      最近更新 更多