Added XML::Element#get

This method can be used to directly retrieve an attribute value.
This commit is contained in:
Yorick Peterse 2014-09-10 19:03:32 +02:00
parent e2dab952d0
commit 6d19c9b311
2 changed files with 32 additions and 3 deletions

View File

@ -55,7 +55,8 @@ module Oga
end
##
# Returns the attribute of the given name.
# Returns an attribute matching the given name (with or without the
# namespace).
#
# @example
# # find an attribute that only has the name "foo"
@ -64,8 +65,10 @@ module Oga
# # find an attribute with namespace "foo" and name bar"
# attribute('foo:bar')
#
# @param [String] name
# @return [String]
# @param [String|Symbol] name The name (with or without the namespace)
# of the attribute.
#
# @return [Oga::XML::Attribute]
#
def attribute(name)
name, ns = split_name(name)
@ -79,6 +82,20 @@ module Oga
alias_method :attr, :attribute
##
# Returns the value of the given attribute.
#
# @example
# element.get('class') # => "container"
#
# @see [#attribute]
#
def get(name)
found = attribute(name)
return found ? found.value : nil
end
##
# Returns the namespace of the element.
#

View File

@ -89,6 +89,18 @@ describe Oga::XML::Element do
end
end
context '#get' do
before do
attr = Oga::XML::Attribute.new(:name => 'foo', :value => 'bar')
@element = described_class.new(:attributes => [attr])
end
example 'return the value of an attribute' do
@element.get('foo').should == 'bar'
end
end
context '#namespace' do
before do
@namespace = Oga::XML::Namespace.new(:name => 'x')