Module: Ox::HasAttrs

Included in:
Element, Instruct
Defined in:
lib/ox/hasattrs.rb

Overview

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.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(id, *args, &block) ⇒ String|nil

Handles the 'easy' API that allows navigating a simple XML by referencing attributes by name.

Parameters:

  • id (Symbol)

    element or attribute name

Returns:

  • (String|nil)

    the attribute value

Raises:

  • (NoMethodError)

    if no match is found


39
40
41
42
43
44
45
46
# File 'lib/ox/hasattrs.rb', line 39

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

Instance Method Details

#[](attr) ⇒ Object

Returns the value of an attribute.

Parameters:

  • attr (Symbol|String)

    attribute name or key to return the value for


20
21
22
23
# File 'lib/ox/hasattrs.rb', line 20

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

#[]=(attr, value) ⇒ Object

Adds or set an attribute of the Instruct.

Parameters:

  • attr (Symbol|String)

    attribute name or key

  • value (Object)

    value for the attribute


28
29
30
31
32
# File 'lib/ox/hasattrs.rb', line 28

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

#attributesHash

Returns all the attributes of the Instruct as a Hash.

Returns:

  • (Hash)

    all attributes and attribute values.


13
14
15
16
# File 'lib/ox/hasattrs.rb', line 13

def attributes
  @attributes = { } if !instance_variable_defined?(:@attributes) or @attributes.nil?
  @attributes
end