如何在常规 Ruby 代码(非 Rails)中使用 strip_tags?
我需要将 HTML 转换为纯文本。 ActionView 的 SanitizeHelper 中有一个很好的函数可以执行此操作,但我无法理解如何引用它并在简单的 test.rb 文件中使用它。
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
我希望能够调用 strip_tags("lol") => “哈哈”
I need to turn HTML into plain text. There's a nice function that does that in ActionView's SanitizeHelper, but I have trouble understanding how I can reference it and use it in a simple test.rb file.
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
I would like to be able to call strip_tags("<b>lol</b>") => "lol"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这个问题很老了,但我最近也遇到了同样的问题。我找到了一个简单的解决方案:gem sanitize。它很轻,工作正常,如果您需要的话,还有其他选项。
The question is quite old, but I had the same problem recently. I found a simple solution: gem sanitize. It's light, works fine and has additional options if you need them.
ActiveSupport 是唯一支持挑选单个组件的 Rails 框架。其他框架(包括 ActionView)必须全部被 require:
请注意,此 require 不一定会加载所有 ActionView。除非线程安全要求自动加载立即发生,否则它只是设置自动加载并需要公共依赖项。这意味着在 require 之后,如果您引用例如
ActionView::Helpers::SanitizeHelper
,它将导致action_view/helpers /sanitize_helper.rb
被要求。因此,使用 ActionView 完成您想要的任务的正确且受支持的方法如下
:我这个答案主要基于对此问题的讨论。
ActiveSupport is the only Rails framework that supports cherry-picking individual components. The other frameworks, including ActionView, must be required en-masse:
Note that this require won't necessarily load all of ActionView. Barring situations where thread-safety requires that autoloads happen eagerly, it merely sets up autoloads and requires common dependencies. That means that following the require, if you reference, e.g.
ActionView::Helpers::SanitizeHelper
, it will causeaction_view/helpers /sanitize_helper.rb
to be required.Therefore the correct, supported way to accomplish what you desire using ActionView is the following:
This isn't well-documented; I based this answer primarily off of the discussion on this issue.
我相信这应该足够了:
您也可以使用 Nokogiri:
您仍然可以通过执行以下操作来使用 Rails:
I believe this should be enough:
You can use Nokogiri as well:
You still can go with the Rails one by doing something like:
如果您不经常使用它,那么您可以使用:
否则您可以在 test_helper.rb 文件中定义一个方法,如下所示:
然后在 test.rb 文件中,使用如下所示:
If you don't use it very often, then you can use:
else you can define a method in test_helper.rb file like:
And then in your test.rb file, use this like:
这个问题很老了,但是您可以在
test.rb
中调用它,如下所示:The question is quite old, but you can call it in your
test.rb
like this:通过这个例子:
这对我有帮助:
输出:
With this example:
This helped me:
Output:
理想情况下,您需要并包含
ActionView::Helpers::SanitizeHelper
但当您这样做时,有几个依赖项不会包含在内。您可以要求他们自己能够使用strip_tags
。这是假设您安装了 Rails 3 gems。
Ideally you would require and include
ActionView::Helpers::SanitizeHelper
but there are several dependencies that don't get included when you do that. You can require them yourself to be able to usestrip_tags
.This is assuming you have rails 3 gems installed.