Re: Sample code for displaying a MIME email message on a web

Olivier Dirrenberger
Fri, 17 Aug 2007 09:23:41 -0000

Olivier Dirrenberger wrote:
> Joshua Baer wrote:
>> Sorry one last question on TextHelper... I can call sanitize from
>> within a view (.rhtml file) no problem, but when I try to use it
>> within a controller or model it complains that the method is unknown.
>> What do I need to require/include to reference sanitize from within a
>> controller or model?
>>
>> ~Josh
>
> Just copy this on your application.rb
>
>   def strip_tags(html)
>     return html if html.blank?
>     if html.index("<")
>       text = ""
>       tokenizer = HTML::Tokenizer.new(html)
>
>       while token = tokenizer.next
>         node = HTML::Node.parse(nil, 0, 0, token, false)
>         # result is only the content of any Text nodes
>         text << node.to_s if node.class == HTML::Text
>       end
>       # strip any comments, and if they have a newline at the end (ie.
> line with
>       # only a comment) strip that too
> text.gsub(/ [\n]?/m, "")
>     else
>       html # already plain text
>     end
Oups, if you want the sanitize this is this sample code :

  def sanitize(html)
    # only do this if absolutely necessary
    if html.index("<")
      tokenizer = HTML::Tokenizer.new(html)
      new_text = ""

      while token = tokenizer.next
        node = HTML::Node.parse(nil, 0, 0, token, false)
        new_text << case node
          when HTML::Tag
            if VERBOTEN_TAGS.include?(node.name)
              node.to_s.gsub(/</, "&lt;")
            else
              if node.closing != :close
                node.attributes.delete_if { |attr,v| attr =~
VERBOTEN_ATTRS }
                %w(href src).each do |attr|
                  node.attributes.delete attr if node.attributes[attr]
=~ /^javascript:/i
                end
              end
              node.to_s
            end
          else
            node.to_s.gsub(/</, "&lt;")
        end
      end

      html = new_text
    end

    html
  end
--
Posted via http://www.ruby-forum.com/.