~singpolyma/sgx-jmp

c3795a6dd00dfe8a0d19a85ab81aa25ecb3a51d8 — Stephen Paul Weber 1 year, 8 months ago 9d3db6e
OOB helper

https://xmpp.org/extensions/xep-0066.html
2 files changed, 103 insertions(+), 0 deletions(-)

A lib/oob.rb
A test/test_oob.rb
A lib/oob.rb => lib/oob.rb +54 -0
@@ 0,0 1,54 @@
# frozen_string_literal: true

require "blather"

class OOB < Blather::XMPPNode
	register :oob, "jabber:x:oob"

	def self.new(url=nil, desc: nil)
		new_node = super :x

		case url
		when Nokogiri::XML::Node
			new_node.inherit url
		else
			new_node.url = url if url
			new_node.desc = desc if desc
		end

		new_node
	end

	def self.find_or_create(parent)
		if (found_x = parent.find("ns:x", ns: registered_ns).first)
			x = new(found_x)
			found_x.remove
		else
			x = new
		end
		parent << x
		x
	end

	def url
		find("ns:url", ns: self.class.registered_ns).first&.content
	end

	def url=(u)
		remove_children :url
		i = Niceogiri::XML::Node.new(:url, document, namespace)
		i.content = u
		self << i
	end

	def desc
		find("ns:desc", ns: self.class.registered_ns).first&.content
	end

	def desc=(d)
		remove_children :desc
		i = Niceogiri::XML::Node.new(:desc, document, namespace)
		i.content = d
		self << i
	end
end

A test/test_oob.rb => test/test_oob.rb +49 -0
@@ 0,0 1,49 @@
# frozen_string_literal: true

require "oob"

class OOBTest < Minitest::Test
	def test_new
		oob = OOB.new
		assert_kind_of OOB, oob
		assert_nil oob.url
		assert_nil oob.desc
	end

	def test_new_with_node
		assert_kind_of OOB, OOB.new(Blather::XMPPNode.new)
	end

	property(:new_with_attrs) { [string(:alnum), string] }
	def new_with_attrs(u, d)
		oob = OOB.new(u, desc: d)
		assert_kind_of OOB, oob
		assert_equal u, oob.url
		assert_equal d, oob.desc
	end

	def test_find_or_create_not_found
		assert_kind_of OOB, OOB.find_or_create(Blather::XMPPNode.new)
	end

	def test_find_or_create_found
		parent = Blather::XMPPNode.new
		parent << OOB.new("http://example.com")
		assert_kind_of OOB, OOB.find_or_create(parent)
		assert_equal "http://example.com", OOB.find_or_create(parent).url
	end

	property(:url) { string(:alnum) }
	def url(u)
		oob = OOB.new
		oob.url = u
		assert_equal u, oob.url
	end

	property(:desc) { string }
	def desc(d)
		oob = OOB.new
		oob.desc = d
		assert_equal d, oob.desc
	end
end