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
38 if block && block.arity == 2
39 # If the block takes two arguments, pass new content and old
40 # content.
41 block.call(rendered, content)
42 elsif block
43 # One argument is just the new content.
44 block.call(rendered)
45 else
46 # No block? No problem!
47 rendered
48 end
49 end
50 end
51
52 def add_markup(regexp, &block)
53 @@markups[regexp] = block
54 end
55
56 def can_render?(filename)
57 !!renderer(filename)
58 end
59
60 def renderer(filename)
61 @@markups.each do |key, value|
62 if Regexp.compile("\\.(#{key})$") =~ filename
63 return value
64 end
65 end
66 nil
67 end
68
69 def execute(command, target)
70 out = ''
71 Open3.popen3(command) do |stdin, stdout, _|
72 stdin.puts target
73 stdin.close
74 out = stdout.read
75 end
76 out.gsub("\r", '')
77 rescue Errno::EPIPE
78 ""
79 end
80
81 # Define markups
82 instance_eval File.read(File.dirname(__FILE__) + '/markups.rb')
83 end
84end