How can I use strip_tags in regular Ruby code (non-rails)?

前端 未结 8 1455
广开言路
广开言路 2020-12-31 00:09

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

相关标签:
8条回答
  • 2020-12-31 00:34

    The question is quite old, but you can call it in your test.rb like this:

    ActionController::Base.helpers.strip_tags("<b>lol</b>") => "lol"
    
    0 讨论(0)
  • 2020-12-31 00:36

    I believe this should be enough:

    "<b>lol</b>".gsub(/<[^>]*>/ui,'') #=> lol
    

    You can use Nokogiri as well:

    require 'rubygems'
    require 'nokogiri'
    doc = Nokogiri::HTML("<b>lol</b>")
    doc.text #=> "lol"
    

    You still can go with the Rails one by doing something like:

    require 'rubygems'
    require 'action_view'
    
    class Foo
      include ActionView::Helpers::SanitizeHelper
    
      def test
        strip_tags("<b>lol</b>")
      end
    end
    
    f = Foo.new
    puts f.test #=> lol
    
    0 讨论(0)
提交回复
热议问题