Types in tables

Stephen Paul Weber created

Change summary

forms/customer_cdr.rb      |  4 ++--
lib/form_table.rb          | 23 +++++++++++++++++++++--
test/test_form_template.rb | 24 ++++++++++++++++++++++++
3 files changed, 47 insertions(+), 4 deletions(-)

Detailed changes

forms/customer_cdr.rb 🔗

@@ -3,9 +3,9 @@ title "Call History"
 
 table(
 	@cdrs,
-	start: "Start",
+	start: { label: "Start", datatype: "xs:dateTime" },
 	direction: "Direction",
-	tel: "Number",
+	tel: { label: "Number", datatype: "html:tel" },
 	disposition: "Status",
 	duration: "Duration",
 	formatted_rate: "Rate",

lib/form_table.rb 🔗

@@ -9,8 +9,8 @@ class FormTable
 	def add_to_form(form)
 		Nokogiri::XML::Builder.with(form) do |xml|
 			xml.reported do
-				@cols.each do |var, label|
-					xml.field(var: var.to_s, label: label.to_s)
+				@cols.each do |var, opts|
+					xml.field(var: var.to_s, **fargs(opts), &validate(xml, opts))
 				end
 			end
 
@@ -20,6 +20,25 @@ class FormTable
 
 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

test/test_form_template.rb 🔗

@@ -130,4 +130,28 @@ class FormTemplateTest < Minitest::Test
 		form = template.render(arg: "abc")
 		assert_equal "abc", form.at("whoever").content
 	end
+
+	def test_table
+		template = FormTemplate.new(<<~TEMPLATE)
+			form!
+			table(
+				@arg,
+				one: "One",
+				two: { label: "Two", datatype: "xs:integer" },
+				three: { label: "Three", type: "jid-single" }
+			)
+		TEMPLATE
+		form = template.render(arg: [OpenStruct.new(one: 1, two: 2, three: 3)])
+		assert_equal 3, form.at("reported").children.length
+		assert_equal "one", form.at("reported").children[0][:var]
+		assert_equal "two", form.at("reported").children[1][:var]
+		assert_equal(
+			"xs:integer",
+			form.at("reported").children[1].at_xpath(
+				"./ns:validate", ns: "http://jabber.org/protocol/xdata-validate"
+			)[:datatype]
+		)
+		assert_equal "three", form.at("reported").children[2][:var]
+		assert_equal "jid-single", form.at("reported").children[2][:type]
+	end
 end