all repos — markup @ v0.2.0

The code we use to render README.your_favorite_markup

lib/github/markup.rb (view raw)

 1begin
 2  require 'open3_detach'
 3rescue LoadError
 4  require 'open3'
 5end
 6
 7module GitHub
 8  module Markup
 9    extend self
10    @@markups = {}
11
12    def render(filename, content)
13      if proc = renderer(filename)
14        proc[content]
15      else
16        content
17      end
18    end
19
20    def markup(file, pattern, &block)
21      require file.to_s
22      add_markup(pattern, &block)
23    rescue LoadError
24      nil
25    end
26
27    def command(command, regexp, &block)
28      command = command.to_s
29
30      if File.exists?(file = File.dirname(__FILE__) + "/commands/#{command}")
31        command = file
32      end
33
34      add_markup(regexp) do |content|
35        rendered = execute(command, content)
36        rendered = rendered.to_s.empty? ? content : rendered
37        block ? block.call(rendered) : rendered
38      end
39    end
40
41    def add_markup(regexp, &block)
42      @@markups[regexp] = block
43    end
44
45    def can_render?(filename)
46      !!renderer(filename)
47    end
48
49    def renderer(filename)
50      @@markups.each do |key, value|
51        if Regexp.compile("\\.(#{key})$") =~ filename
52          return value
53        end
54      end
55      nil
56    end
57
58    def execute(command, target)
59      out = ''
60      Open3.popen3(command) do |stdin, stdout, _|
61        stdin.puts target
62        stdin.close
63        out = stdout.read
64      end
65      out.gsub("\r", '')
66    rescue Errno::EPIPE
67      ""
68    end
69
70    # Define markups
71    instance_eval File.read(File.dirname(__FILE__) + '/markups.rb')
72  end
73end