Methods for adding attributes to elements.

The methods XML::Element#add_attribute and XML::Element#set can be used to more
easily add attributes to elements. The first method simply adds an Attribute
instance and links it to the element. This allows for fine grained control over
what data the attribute should contain. The second method ("set") simply sets an
attribute based on a name and value, optionally creating the attribute if it
doesn't already exist.
This commit is contained in:
Yorick Peterse 2014-09-10 23:55:29 +02:00
parent 6cb2d54875
commit c45d32a37e
2 changed files with 99 additions and 0 deletions

View File

@ -96,6 +96,48 @@ module Oga
return found ? found.value : nil
end
##
# Adds a new attribute to the element.
#
# @param [Oga::XML::Attribute] attribute
#
def add_attribute(attribute)
attribute.element = self
attributes << attribute
end
##
# Sets the value of an attribute to the given value. If the attribute does
# not exist it is created automatically.
#
# @param [String] name The name of the attribute, optionally including the
# namespace.
#
# @param [String] value The new value of the attribute.
#
def set(name, value)
found = attribute(name)
if found
found.value = value
else
if name.include?(':')
ns, name = name.split(':')
else
ns = nil
end
attr = Attribute.new(
:name => name,
:namespace_name => ns,
:value => value
)
add_attribute(attr)
end
end
##
# Returns the namespace of the element.
#

View File

@ -101,6 +101,63 @@ describe Oga::XML::Element do
end
end
context '#add_attribute' do
before do
@element = described_class.new
@attribute = Oga::XML::Attribute.new(:name => 'foo', :value => 'bar')
end
example 'add an Attribute to the element' do
@element.add_attribute(@attribute)
@element.attribute('foo').should == @attribute
end
example 'set the element of the attribute when adding it' do
@element.add_attribute(@attribute)
@attribute.element.should == @element
end
end
context '#set' do
before do
@element = described_class.new
@element.register_namespace('x', 'test')
end
example 'add a new attribute' do
@element.set('class', 'foo')
@element.get('class').should == 'foo'
end
example 'add a new attribute with a namespace' do
@element.set('x:bar', 'foo')
@element.get('x:bar').should == 'foo'
end
example 'set the namespace of an attribute' do
@element.set('x:bar', 'foo')
attr = @element.attribute('x:bar')
attr.namespace.is_a?(Oga::XML::Namespace).should == true
end
example 'overwrite the value of an existing attribute' do
attr = Oga::XML::Attribute.new(:name => 'foo', :value => 'bar')
@element.add_attribute(attr)
@element.set('foo', 'baz')
@element.get('foo').should == 'baz'
end
end
context '#namespace' do
before do
@namespace = Oga::XML::Namespace.new(:name => 'x')