]> git.openstreetmap.org Git - rails.git/blob - lib/rich_text.rb
Add some tests for the RichText module
[rails.git] / lib / rich_text.rb
1 module RichText
2   def self.new(format, text)
3     case format
4     when "html"; HTML.new(text || "")
5     when "markdown"; Markdown.new(text || "")
6     when "text"; Text.new(text || "")
7     else; nil
8     end
9   end
10
11   class Base < String
12     def spam_score
13       link_count = 0
14       link_size = 0
15
16       doc = Nokogiri::HTML(to_html)
17
18       if doc.content.length > 0
19         doc.xpath("//a").each do |link|
20           link_count += 1
21           link_size += link.content.length
22         end
23
24         link_proportion = link_size.to_f / doc.content.length.to_f
25       else
26         link_proportion = 0
27       end
28
29       return [link_proportion - 0.2, 0.0].max * 200 + link_count * 20
30     end
31
32   protected
33
34     def linkify(text)
35       if text.html_safe?
36         Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow")).html_safe
37       else
38         Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow"))
39       end
40     end
41   end
42
43   class HTML < Base
44     include ActionView::Helpers::TextHelper
45     include ActionView::Helpers::TagHelper
46
47     def to_html
48       linkify(sanitize(simple_format(self)))
49     end
50
51     def to_text
52       self
53     end
54
55   private
56
57     def sanitize(text)
58       Sanitize.clean(text, Sanitize::Config::OSM).html_safe
59     end
60   end
61
62   class Markdown < Base
63     def to_html
64       html_parser.render(self).html_safe
65     end
66
67     def to_text
68       self
69     end
70
71   private
72
73     def html_parser
74       @@html_renderer ||= Renderer.new({
75         :filter_html => true, :safe_links_only => true
76       })
77       @@html_parser ||= Redcarpet::Markdown.new(@@html_renderer, {
78         :no_intra_emphasis => true, :autolink => true, :space_after_headers => true
79       })
80     end
81
82     class Renderer < Redcarpet::Render::XHTML
83       def link(link, title, alt_text)
84         "<a rel=\"nofollow\" href=\"#{link}\">#{alt_text}</a>"
85       end
86
87       def autolink(link, link_type)
88         if link_type == :email
89           "<a rel=\"nofollow\" href=\"mailto:#{link}\">#{link}</a>"
90         else
91           "<a rel=\"nofollow\" href=\"#{link}\">#{link}</a>"
92         end
93       end 
94     end
95   end
96
97   class Text < Base
98     include ActionView::Helpers::TextHelper
99
100     def to_html
101       linkify(simple_format(ERB::Util.html_escape(self)))
102     end
103
104     def to_text
105       self
106     end
107   end
108 end