Sha256: 92c74a43a42cba90371d72555348f5785e53e9d2a930f37c9411cdf77812f332

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

# == XMLNode
#
# Representation of an XML node. Inherits from String and includes some
# useful methods for namespaces, attributes, body content etc.
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 this node to snake_case.
  def to_snake_case!
    gsub!(/[A-Z]/, '_\0')
    gsub!(/^_/, '')
    downcase!
  end

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

  # Checks if 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)
    namespaces.each do |namespace, nodes|
      @namespace = namespace if self_included? nodes
    end unless namespaces.nil? || namespaces.empty?
  end

  # Returns this node as an 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
    @namespace ? "#{@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
    @body ? @body : ""
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
smacks-apricoteatsgorilla-0.5.1 lib/apricoteatsgorilla/xml_node.rb