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 = nil)
13 content ||= File.read(filename)
14
15 if proc = renderer(filename)
16 proc[content]
17 else
18 content
19 end
20 end
21
22 def markup(file, pattern, &block)
23 require file.to_s
24 add_markup(pattern, &block)
25 rescue LoadError
26 nil
27 end
28
29 def command(command, regexp, &block)
30 command = command.to_s
31
32 if File.exists?(file = File.dirname(__FILE__) + "/commands/#{command}")
33 command = file
34 end
35
36 add_markup(regexp) do |content|
37 rendered = execute(command, content)
38 rendered = rendered.to_s.empty? ? content : rendered
39
40 if block && block.arity == 2
41 # If the block takes two arguments, pass new content and old
42 # content.
43 block.call(rendered, content)
44 elsif block
45 # One argument is just the new content.
46 block.call(rendered)
47 else
48 # No block? No problem!
49 rendered
50 end
51 end
52 end
53
54 def add_markup(regexp, &block)
55 @@markups[regexp] = block
56 end
57
58 def can_render?(filename)
59 !!renderer(filename)
60 end
61
62 def renderer(filename)
63 @@markups.each do |key, value|
64 if Regexp.compile("\\.(#{key})$") =~ filename
65 return value
66 end
67 end
68 nil
69 end
70
71 def execute(command, target)
72 out = ''
73 Open3.popen3(command) do |stdin, stdout, _|
74 stdin.puts target
75 stdin.close
76 out = stdout.read
77 end
78 out.gsub("\r", '')
79 rescue Errno::EPIPE
80 ""
81 end
82
83 # Define markups
84 instance_eval File.read(File.dirname(__FILE__) + '/markups.rb')
85 end
86end