]> git.openstreetmap.org Git - rails.git/blob - lib/rich_text.rb
9c4a24fd54a11c18e7d50d3b65e8b137e768dc24
[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 ||= Redcarpet::Render::XHTML.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   end
82
83   class Text < Base
84     include ActionView::Helpers::TextHelper
85
86     def to_html
87       linkify(simple_format(ERB::Util.html_escape(self)))
88     end
89
90     def to_text
91       self
92     end
93   end
94 end