lib/xommelier/xml/element/serialization.rb in xommelier-0.1.21 vs lib/xommelier/xml/element/serialization.rb in xommelier-0.1.22

- old
+ new

@@ -1,8 +1,10 @@ require 'xommelier/xml/element' require 'active_support/concern' require 'active_support/core_ext/object/blank' +require 'active_support/core_ext/hash/slice' +require 'active_support/core_ext/hash/except' require 'nokogiri' module Xommelier module Xml class Element @@ -10,10 +12,11 @@ extend ActiveSupport::Concern SERIALIZATION_OPTIONS = { encoding: 'utf-8' } + SAVE_OPTIONS = [:save_with, :indent_text, :indent] module ClassMethods def from_xml(xml, options = {}) new({}, options).tap do |doc| doc.from_xml(xml, options) @@ -43,11 +46,10 @@ def from_xml(xml, options = {}) if IO === xml || String === xml xml = Nokogiri::XML(xml) end @_xml_node = options.delete(:node) { xml.at_xpath(element_xpath(xml.document, element_name)) } - validate if options[:validate] if text? && @_xml_node.inner_html.present? self.text = @_xml_node.inner_html end @@ -61,10 +63,13 @@ end alias_method :from_xommelier, :from_xml def to_xml(options = {}) options = SERIALIZATION_OPTIONS.merge(options) + save_options = options.slice(:encoding, *SAVE_OPTIONS) + options = options.except(*SAVE_OPTIONS) + element_name = options.delete(:element_name) { self.element_name } element_name = element_name.to_s element_name << '_' if %w(text class id).include?(element_name) xmlns = options[:ns] || self.xmlns if options[:builder] # Non-root element @@ -107,11 +112,11 @@ end end end xml.text(@text) if respond_to?(:text) end.instance_variable_get(:@node) - builder.to_xml + builder.to_xml(save_options) end alias_method :to_xommelier, :to_xml def to_hash attributes.dup.tap do |hash| @@ -131,10 +136,15 @@ end hash[:text] = text if text? end end + # @return [Nokogiri::XML::Node] + def to_nokogiri + ensure_xml_document.root + end + def <=>(other) if text? && other.is_a?(String) text.to_s <=> other else super @@ -187,9 +197,14 @@ end end def xml_document @_xml_node.try(:document) + end + + def ensure_xml_document + to_xml unless xml_document + xml_document end def xmlns_xpath(xml_document = self.xml_document) self.class.xmlns_xpath(xml_document) end