Class

Ruby code posted
created at 11 Jul 20:07, updated at 11 Jul 20:07

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class CodeFormatter
  def initialize(text)
    @text = text
  end

  def to_html
    text = @text.clone
    codes = []
    text.gsub!(/^``` ?(.*?)\r?\n(.+?)\r?\n```\r?$/m) do |match|
      code = { :id => "CODE#{codes.size}ENDCODE", :name => ($1.empty? ? nil : $1), :content => $2 }
      codes << code
      "\n\n#{code[:id]}\n\n"
    end
    html = Redcarpet.new(text, :filter_html, :hard_wrap, :autolink, :no_intraemphasis).to_html
    codes.each do |code|
      html.sub!("<p>#{code[:id]}</p>") do
        <<-EOS
          <div class="code_block">
            <div class="code_header">
              #{CGI.escapeHTML(code[:name].to_s)}
              #{clippy(code[:content])}
            </div>
            #{CodeRay.scan(code[:content], language(code[:name])).div(:css => :class)}
          </div>
        EOS
      end
    end
    html
  end

  def language(path)
    case path
    when /\.yml$/ then "yaml"
    when /\.js$/ then "java_script"
    when /\.scss$/ then "css"
    when /\.erb$/, /\.html$/ then "rhtml"
    when /\.rb$/, /\.rake$/, /\.gemspec/, /file$/, /console$/ then "ruby"
    when /\./ then path[/\.([^.]+?)$/, 1]
    else path
    end
  end

  def clippy(text)
    id = "clippy_#{rand(10000000)}"
    <<-EOS
      <div id="#{id}" class="clippy">
        <span style="display:none" class="clippy_code">#{CGI.escapeHTML(text)}</span>
        <span class="clippy_label"></span>
        <object type="application/x-shockwave-flash" data="/flash/clippy.swf" width="14" height="14" id="#{id}_flash">
        <param name="movie" value="/flash/clippy.swf" />
        <param name="allowScriptAccess" value="always" />
        <param name="quality" value="high" />
        <param name="scale" value="noscale" />
        <param name="FlashVars" value="target=#{CGI.escape('#' + id)}" />
        <param name="bgcolor" value="#E0E0E0" />
        </object>
      </div>
    EOS
  end
end
1.91 KB in 9 ms with coderay