Sha256: d83502e67692491a16483849a8a64d4764610972f36d4d72dd73c84be43ba4cd

Contents?: true

Size: 1.93 KB

Versions: 2

Compression:

Stored size: 1.93 KB

Contents

# == XMLNode
#
# Representation of an XML node.
class XMLNode < String

  # Hash of attributes.
  attr_writer :attributes

  # Body content.
  attr_writer :body

  # Strips the namespace from this node.
  def strip_namespace!
    sub!(/.+:(.+)/, '\1')
  end

  # Converts the name of this node to snake_case.
  def to_snake_case!
    self.gsub!(/[A-Z]/, '_\0')
    self.gsub!(/^_/, '')
    self.downcase!
  end

  # Converts the name of this node to lowerCamelCase.
  def to_lower_camel_case!
    self.gsub!(/_(.)/) { $1.upcase }
  end

  # Checks if the name of this node is included in a given Hash of +namespaces+
  # and sets the namespace for this node in case it was found in the Hash.
  def namespace_from_hash!(namespaces)
    return if namespaces.nil? || namespaces.empty?

    namespaces.each do |namespace, nodes|
      @namespace = namespace if self_included?(nodes)
    end
  end

  # Returns this node as a complete XML tag including a +namespace+, +attributes+
  # and a +body+ in case these values were supplied.
  def to_tag
    return "<#{namespace}#{self}#{attributes} />" unless @body
    "<#{namespace}#{self}#{attributes}>#{body}</#{namespace}#{self}>"
  end

private

  # Returns +true+ if self as a String or a Symbol is included in a given
  # +array+. Returns +false+ otherwise.
  def self_included?(array)
    array.include?(self.to_s) || array.include?(self.to_sym)
  end

  # Returns the namespace of this node. Defaults to an empty String in case
  # no namespace was defined.
  def namespace
    return "" if @namespace.nil?
    "#{@namespace}:"
  end

  # Returns the attributes of this node. Defaults to an empty String in case
  # no attributes were defined.
  def attributes
    return "" if @attributes.nil?
    @attributes.map { |key, value| %Q( xmlns:#{key}="#{value}") }
  end

  # Returns the body of this node. Defaults to an empty String in case no body
  # was defined.
  def body
    return "" if @body.nil?
    @body
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
smacks-apricoteatsgorilla-0.4.6 lib/apricoteatsgorilla/xml_node.rb
smacks-apricoteatsgorilla-0.4.7 lib/apricoteatsgorilla/xml_node.rb