~singpolyma/sgx-jmp

ref: 5d2a8e6daab8a06f14a5554e85c8a2a90d994006 sgx-jmp/lib/form_template.rb -rw-r--r-- 1.1 KiB
5d2a8e6dStephen Paul Weber Allow user to search for numbers over XMPP 11 months ago
                                                                                
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
62
63
64
# frozen_string_literal: true

require "blather"

class FormTemplate
	def initialize(template, filename="template", **kwargs)
		@args = kwargs
		@template = template
		@filename = filename
		freeze
	end

	def self.render(path, **kwargs)
		full_path = File.dirname(__dir__) + "/forms/#{path}.rb"
		new(File.read(full_path), full_path, **kwargs).render
	end

	def render(**kwargs)
		one = OneRender.new(**@args.merge(kwargs))
		one.instance_eval(@template, @filename)
		one.form
	end

	class OneRender
		def initialize(**kwargs)
			kwargs.each do |k, v|
				instance_variable_set("@#{k}", v)
			end
			@__form = Blather::Stanza::X.new
			@__builder = Nokogiri::XML::Builder.with(@__form)
		end

		def form!
			@__type_set = true
			@__form.type = :form
		end

		def result!
			@__type_set = true
			@__form.type = :result
		end

		def title(s)
			@__form.title = s
		end

		def instructions(s)
			@__form.instructions = s
		end

		def field(**kwargs)
			@__form.fields = @__form.fields + [kwargs]
		end

		def xml
			@__builder
		end

		def form
			raise "Type never set" unless @__type_set
			@__form
		end
	end
end