~singpolyma/sgx-jmp

sgx-jmp/lib/form_table.rb -rw-r--r-- 936 bytes
bdf6280cStephen Paul Weber Voicemail timeout field improvements 2 days 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
# frozen_string_literal: true

class FormTable
	def initialize(rows, **cols)
		@cols = cols
		@rows = rows
	end

	def add_to_form(form)
		Nokogiri::XML::Builder.with(form) do |xml|
			xml.reported do
				@cols.each do |var, opts|
					xml.field(var: var.to_s, **fargs(opts), &validate(xml, opts))
				end
			end

			add_rows_to_xml(xml)
		end
	end

protected

	def fargs(opts)
		if opts.is_a?(Hash)
			opts.slice(:label, :type)
		else
			{ label: opts.to_s }
		end
	end

	def validate(xml, opts)
		proc do
			if opts.is_a?(Hash) && opts[:datatype]
				xml.validate(
					xmlns: "http://jabber.org/protocol/xdata-validate",
					datatype: opts[:datatype]
				) { xml.basic }
			end
		end
	end

	def add_rows_to_xml(xml)
		@rows.each do |row|
			xml.item do
				row.each.with_index do |val, idx|
					xml.field(var: @cols.keys[idx].to_s) do
						[val].compact.flatten.each { |x| xml.value x.to_s }
					end
				end
			end
		end
	end
end