]> git.openstreetmap.org Git - rails.git/blob - lib/rich_text.rb
ec5e9e473789a9d70c7e8fb770cac51e14be8137
[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     else; nil
7     end
8   end
9
10   class HTML < String
11     include ActionView::Helpers::TextHelper
12     include ActionView::Helpers::TagHelper
13
14     def to_html
15       linkify(sanitize(simple_format(self)))
16     end
17
18     def to_text
19       self
20     end
21
22   private
23
24     def sanitize(text)
25       Sanitize.clean(text, Sanitize::Config::OSM).html_safe
26     end
27
28     def linkify(text)
29       if text.html_safe?
30         Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow")).html_safe
31       else
32         Rinku.auto_link(text, :urls, tag_options(:rel => "nofollow"))
33       end
34     end
35   end
36
37   class Markdown < String
38     def to_html
39       html_parser.render(self).html_safe
40     end
41
42     def to_text
43       self
44     end
45
46   private
47
48     def html_parser
49       @@html_renderer ||= Redcarpet::Render::XHTML.new({
50         :filter_html => true, :safe_links_only => true
51       })
52       @@html_parser ||= Redcarpet::Markdown.new(@@html_renderer, {
53         :no_intra_emphasis => true, :autolink => true, :space_after_headers => true
54       })
55     end
56   end
57 end