Sha256: 2ac6417ef064fc545994e0f100c48ebe74f9a8441eaf066b4e405c2a4507fdd2

Contents?: true

Size: 1.93 KB

Versions: 13

Compression:

Stored size: 1.93 KB

Contents

module Plivo
  module XML
    class Element
      class << self
        attr_accessor :valid_attributes, :nestables
      end
      @nestables = []
      @valid_attributes = []

      attr_accessor :node, :name

      def initialize(body = nil, attributes = {})
        @name = self.class.name.split('::')[2]
        @body = body
        @node = REXML::Element.new @name
        attributes.each do |k, v|
          if self.class.valid_attributes.include?(k.to_s)
            @node.attributes[k.to_s] = convert_value(v)
          else
            raise PlivoXMLError, "invalid attribute #{k} for #{@name}"
          end
        end

        @node.text = @body if @body

        # Allow for nested "nestable" elements using a code block
        # ie
        # Plivo::XML::Response.new do |r|
        #   r.Dial do |n|
        #     n.Number '+15557779999'
        #   end
        # end
        yield(self) if block_given?
      end

      def method_missing(method, *args, &block)
        # Handle the addElement methods
        method = Regexp.last_match(1).to_sym if method.to_s =~ /^add(.*)/
        # Add the element
        begin
          add(Plivo::XML.const_get(method).new(*args, &block))
        rescue StandardError => e
          raise PlivoXMLError, e.message
        end
      end

      def convert_value(v)
        case v
        when true
          'true'
        when false
          'false'
        when nil
          'none'
        when 'get'
          'GET'
        when 'post'
          'POST'
        else
          v
        end
      end

      def add(element)
        raise PlivoXMLError, 'invalid element' unless element
        if self.class.nestables.include?(element.name)
          @node.elements << element.node
          element
        else
          raise PlivoXMLError, "#{element.name} not nestable in #{@name}"
        end
      end

      def to_xml
        @node.to_s
      end

      def to_s
        @node.to_s
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
plivo-4.3.0 lib/plivo/xml/element.rb
plivo-4.2.0.pre.beta1 lib/plivo/xml/element.rb
plivo-4.1.8 lib/plivo/xml/element.rb
plivo-4.1.7 lib/plivo/xml/element.rb
plivo-4.1.6 lib/plivo/xml/element.rb
plivo-4.1.5 lib/plivo/xml/element.rb
plivo-4.1.4 lib/plivo/xml/element.rb
plivo-4.1.3 lib/plivo/xml/element.rb
plivo-4.1.2 lib/plivo/xml/element.rb
plivo-4.1.1 lib/plivo/xml/element.rb
plivo-4.1.0 lib/plivo/xml/element.rb
plivo-4.0.0 lib/plivo/xml/element.rb
plivo-4.0.0.beta.2 lib/plivo/xml/element.rb