在保存到数据库之前,Rails将纯文本转换为html

时间:2013-11-20 01:38:34

标签: ruby-on-rails json

我们有一个rails应用程序和以json格式发送的消息是纯文本:

{ "TextBody": "To confirm your subscription to 'Blah ads. Location: Blah. Category: buy and sell.', please click on the following link:\r\n\r\nhttps:\/\/domain.com\/confirm\/jBb62m\r\n\r\n\r\nAs we have no control over the content of the feeds we send, consider adding email@domain.com to your address book or spam whitelist to placate any overexcitable spam filters.\r\n\r\nIf you weren't expecting to receive this email, then simply ignore it and we'll go away."}

解析json之后我有一个对象,所以在将这个纯文本保存到数据库之前如何将其转换为html等。

entry.text_body

我无法更改视图代码,因为网站上有太多其他功能使用它。

任何帮助都将不胜感激。

编辑:新问题实际上是如何将其解析为HTML的步骤。用\和自动隐藏等替换\ n。

1 个答案:

答案 0 :(得分:2)

使用strip和以下gsub正则表达式匹配的组合将呈现以下内容:

entry.text_body.strip.gsub(/\s+/, ' ')
#=> "To confirm your subscription to 'Blah ads. Location: Blah. Category: buy and
#   sell.', please click on the following link: https://domain.com/confirm/jBb62m
#   As we have no control over the content of the feeds we send, consider adding 
#   email@domain.com to your address book or spam whitelist to placate any
#   overexcitable spam filters. If you weren't expecting to receive this email, 
#   then simply ignore it and we'll go away."

<强>更新

首先,要使用HTML \r\n标记替换\n<br />换行符,请运行以下gsub正则表达式替换:

'foo\r\nbar'.gsub(/(\r)?\n/, '<br />')
#=> "foo<br />bar"

关于到HTML的URL转换:Rails曾经有一个名为auto_link的视图助手,它会自动将URL转换为完全有效的标记等价物。但是,此功能已deprecated as of Rails 3.1。幸运的是,该功能被抽象为一个名为rails_autolink的宝石。

要安装gem,请将以下内容添加到Gemfile中并运行bundle install

# Gemfile
gem 'rails_autolink'

然后,将库(及其核心依赖项)导入到您希望auto_link功能的任何脚本中:

include ActionView::Helpers::TextHelper
include ActionView::Helpers::UrlHelper
require 'rails_autolink'

url = 'https://domain.com/confirm/jBb62m'
auto_link(url) # Use auto_link(string).gsub(/\"/, '\'') to escape backslashes
#=> <a href='https://domain.com/confirm/jBb62m'>https://domain.com/confirm/jBb62m</a>

email = 'email@domain.com'
auto_link(email)
#=> <a href='mailto:email@domain.com'>email@domain.com</a>

<强>概要

include ActionView::Helpers::TextHelper
include ActionView::Helpers::UrlHelper
require 'rails_autolink'

auto_link(entry.text_body.gsub(/(\r)?\n/, '<br />').strip.gsub(/\s+/, ' '))
#=> "To confirm your subscription to 'Blah ads. Location: Blah. Category: buy 
#   and sell.', please click on the following link:<br /><br /><a 
#   href=\"https://domain.com/confirm/jBb62m\">https://domain.com/confirm/jBb62m
#   </a><br /><br /><br />As we have no control over the content of the feeds we 
#   send, consider adding <a href=\"mailto:email@domain.com\">email@domain.com</a> 
#   to your address book or spam whitelist to placate any overexcitable spam filters.
#   <br /><br />If you weren't expecting to receive this email, then simply ignore 
#   it and we'll go away."