Add a simple "text" format to the RichText module
[rails.git] / lib / rich_text.rb
index ec5e9e473789a9d70c7e8fb770cac51e14be8137..9c4a24fd54a11c18e7d50d3b65e8b137e768dc24 100644 (file)
@@ -3,11 +3,44 @@ module RichText
     case format
     when "html"; HTML.new(text || "")
     when "markdown"; Markdown.new(text || "")
+    when "text"; Text.new(text || "")
     else; nil
     end
   end
 
-  class HTML < String
+  class Base < String
+    def spam_score
+      link_count = 0
+      link_size = 0
+
+      doc = Nokogiri::HTML(to_html)
+
+      if doc.content.length > 0
+        doc.xpath("//a").each do |link|
+          link_count += 1
+          link_size += link.content.length
+        end
+
+        link_proportion = link_size.to_f / doc.content.length.to_f
+      else
+        link_proportion = 0
+      end
+
+      return [link_proportion - 0.2, 0.0].max * 200 + link_count * 20
+    end
+
+  protected
+
+    def linkify(text)
+      if text.html_safe?
+        Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow")).html_safe
+      else
+        Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow"))
+      end
+    end
+  end
+
+  class HTML < Base
     include ActionView::Helpers::TextHelper
     include ActionView::Helpers::TagHelper
 
@@ -24,17 +57,9 @@ module RichText
     def sanitize(text)
       Sanitize.clean(text, Sanitize::Config::OSM).html_safe
     end
-
-    def linkify(text)
-      if text.html_safe?
-        Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow")).html_safe
-      else
-        Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow"))
-      end
-    end
   end
 
-  class Markdown < String
+  class Markdown < Base
     def to_html
       html_parser.render(self).html_safe
     end
@@ -54,4 +79,16 @@ module RichText
       })
     end
   end
+
+  class Text < Base
+    include ActionView::Helpers::TextHelper
+
+    def to_html
+      linkify(simple_format(ERB::Util.html_escape(self)))
+    end
+
+    def to_text
+      self
+    end
+  end
 end