Sha256: 5711ba230e895dab8c18cb265bfc9e59060966ea5cc636c652c1ba30b30500a5

Contents?: true

Size: 1.92 KB

Versions: 41

Compression:

Stored size: 1.92 KB

Contents

module Ox

  # An Object that includes the HasAttrs module can have attributes which are a Hash of String values and either String
  # or Symbol keys.
  #
  # To access the attributes there are several options. One is to walk the attributes. The easiest for simple regularly
  # formatted XML is to reference the attributes simply by name.
  module HasAttrs
    # Returns all the attributes of the Instruct as a Hash.
    # *return* [Hash] all attributes and attribute values.
    def attributes
      @attributes = { } if !instance_variable_defined?(:@attributes) or @attributes.nil?
      @attributes
    end
    
    # Returns the value of an attribute.
    # - +attr+ [Symbol|String] attribute name or key to return the value for
    def [](attr)
      return nil unless instance_variable_defined?(:@attributes) and @attributes.is_a?(Hash)
      @attributes[attr] or (attr.is_a?(String) ? @attributes[attr.to_sym] : @attributes[attr.to_s])
    end

    # Adds or set an attribute of the Instruct.
    # - +attr+ [Symbol|String] attribute name or key
    # - +value+ [Object] value for the attribute
    def []=(attr, value)
      raise "argument to [] must be a Symbol or a String." unless attr.is_a?(Symbol) or attr.is_a?(String)
      @attributes = { } if !instance_variable_defined?(:@attributes) or @attributes.nil?
      @attributes[attr] = value.to_s
    end
    
    # Handles the 'easy' API that allows navigating a simple XML by
    # referencing attributes by name.
    # - +id+ [Symbol] element or attribute name
    # *return* [String|nil] the attribute value
    # _raise_ [NoMethodError] if no match is found
    def method_missing(id, *args, &block)
      ids = id.to_s
      if instance_variable_defined?(:@attributes)
        return @attributes[id] if @attributes.has_key?(id)
        return @attributes[ids] if @attributes.has_key?(ids)
      end
      raise NoMethodError.new("#{ids} not found", name)
    end

  end # HasAttrs
end # Ox

Version data entries

41 entries across 41 versions & 2 rubygems

Version Path
ox-2.14.1 lib/ox/hasattrs.rb
ox-2.14.0 lib/ox/hasattrs.rb
ox-2.13.4 lib/ox/hasattrs.rb
ox-2.13.3 lib/ox/hasattrs.rb
ox-2.13.2 lib/ox/hasattrs.rb
ox-2.13.1 lib/ox/hasattrs.rb
ox-2.12.1 lib/ox/hasattrs.rb
ox-2.12.0 lib/ox/hasattrs.rb
ox-2.11.0 lib/ox/hasattrs.rb
ox-2.10.1 lib/ox/hasattrs.rb
xaiml-0.1.3 vendor/bundle/ruby/2.5.0/gems/ox-2.10.0/lib/ox/hasattrs.rb
xaiml-0.1.2 vendor/bundle/ruby/2.5.0/gems/ox-2.10.0/lib/ox/hasattrs.rb
xaiml-0.1.1 vendor/bundle/ruby/2.5.0/gems/ox-2.10.0/lib/ox/hasattrs.rb
xaiml-0.1.0 vendor/bundle/ruby/2.5.0/gems/ox-2.10.0/lib/ox/hasattrs.rb
ox-2.10.0 lib/ox/hasattrs.rb
ox-2.9.4 lib/ox/hasattrs.rb
ox-2.9.3 lib/ox/hasattrs.rb
ox-2.9.2 lib/ox/hasattrs.rb
ox-2.9.1 lib/ox/hasattrs.rb
ox-2.9.0 lib/ox/hasattrs.rb