forked from stripe-contrib/pagerbot
/
template.rb
61 lines (49 loc) · 1.65 KB
/
template.rb
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
61
require 'ostruct'
module PagerBot::Template
class ErbStruct
def initialize(template_name, hash)
@_template_name = template_name
hash.each do |key, value|
singleton_class.send(:define_method, key) { value }
end
end
def render(adapter=nil)
template_name = @_template_name
unless adapter.nil?
template_name = "#{@_template_name}_#{adapter}"
end
unless PagerBot::Template.template_exists?(template_name)
if adapter == :slack
return render(:irc)
elsif adapter == :hipchat
return render(:slack).split("\n").join("\n<br>")
end
end
template = PagerBot::Template.fetch_template(template_name)
# '>' denotes that erb should trim some whitespace
ERB.new(template, nil, '>').result(binding).strip
end
def utilities
PagerBot::Utilities
end
end
@@cache = {}
def self.fetch_template(template_name)
return @@cache[template_name] unless @@cache[template_name].nil?
templates_dir = File.expand_path(
File.join(File.dirname(__FILE__), "../../templates"))
template_file_list = Dir.entries(templates_dir)
PagerBot.log.debug("Template files: #{template_file_list}")
file_path = File.join(templates_dir, template_name+".erb")
@@cache[template_name] = File.read(file_path)
end
def self.template_exists?(template_name)
templates_dir = File.expand_path(
File.join(File.dirname(__FILE__), "../../templates"))
path = File.join(templates_dir, template_name+".erb")
File.exist?(path)
end
def self.render(template_name, variables={})
ErbStruct.new(template_name, variables)
end
end