Sha256: 612d6a70b116a932cbe196d83bac2259c93bf16e0a83250538487aca2a4dd8bc

Contents?: true

Size: 967 Bytes

Versions: 4

Compression:

Stored size: 967 Bytes

Contents

module Saxy
  class Element
    attr_reader :attributes, :value

    def initialize
      @attributes = {}
      @value = nil
    end

    def set_attribute(name, value)
      name = attribute_name(name)
      attributes[name] ||= []
      attributes[name] << value
    end

    def append_value(string)
      unless (string = string.strip).empty?
        @value ||= ""
        @value << string
      end
    end

    def to_h
      return value unless attributes.any?
      data = attributes.reduce({}) do |memo, (name, value)|
        memo[name.to_sym] = value.size == 1 ? value.first : value
        memo
      end
      data[:contents] = value
      data
    end

    def attribute_name(name)
      underscore(name).to_sym
    end

    private

    def underscore(word)
      word = word.dup
      word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
      word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
      word.tr!("-", "_")
      word.downcase!
      word
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
saxy-0.6.1 lib/saxy/element.rb
saxy-0.6.0 lib/saxy/element.rb
saxy-0.5.2 lib/saxy/element.rb
saxy-0.5.1 lib/saxy/element.rb