Module: GH::Events::Text
Defined Under Namespace
Classes: ErbBinding
Constant Summary collapse
- ASPECTS =
this is a carefully curated list of fields in gh events that might be helpful when filtering events
%i[type action state]
Instance Method Summary collapse
- #render(template, data) ⇒ Object
- #templates_file(dict) ⇒ Object
- #translate(payload, dict) ⇒ Object
-
#validate(response, channel) ⇒ Object
Validate the format of the response in case it’s JSON.
Instance Method Details
#render(template, data) ⇒ Object
84 85 86 |
# File 'lib/gh/events/text.rb', line 84 def render(template, data) ERB.new(JSON.unparse(template)).result(ErbBinding.new(data).get_binding) end |
#templates_file(dict) ⇒ Object
68 69 70 71 72 73 74 75 76 |
# File 'lib/gh/events/text.rb', line 68 def templates_file(dict) preset = File.(File.join(%w(.. .. .. .. res) << "#{dict}.yml"), __FILE__) return preset if File.exists?(preset) return dict if File.exists?(dict.to_s) warn "Could not find dict file: #{dict}" exit(1) end |
#translate(payload, dict) ⇒ Object
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 |
# File 'lib/gh/events/text.rb', line 14 def translate(payload, dict) dict ||= 'plain' templates = YAML.load_file(templates_file(dict)) event = JSON.parse(payload, object_class: OpenStruct) type = GH::Events.typeof(event).to_s # unify event.ref_type = 'branch' if event.ref&.match(/^refs\/heads\//) event.ref_type = 'tag' if event.ref&.match(/^refs\/tags\//) event.ref = event.ref&.split('/')&.last # add type to the event event.type = type # collect the aspects aspects = ASPECTS.map { |a| event.send(a) }.compact # add the specific type (stype) to the event event.stype = aspects * '.' # lookup the template by type and all the specific types _result = aspects.reduce({as: [], ts: []}) do |r, aspect| r[:as] << aspect r[:ts] << templates[r[:as] * '.'] r end template = _result[:ts].compact.last # if the event was set to `false` abort return nil if template === false # if there is no template use a default template ||= templates['no_template'] res = render(template, event).gsub(/[\n\r]+/, '\n') validate(res, dict) res end |
#validate(response, channel) ⇒ Object
Validate the format of the response in case it’s JSON
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/gh/events/text.rb', line 56 def validate(response, channel) return unless channel == "slack" begin JSON.parse(response) rescue Exception => e warn "Rendered template is not valid JSON" warn e exit 1 end response end |