From 7c41fa814fab736ac6e9845ee18e3be6b00f4951 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Wed, 27 Aug 2014 20:24:40 +0200 Subject: [PATCH] Default attribute namespaces. When an attribute is prefixed with "xml" the default namespace should be used automatically. This namespace is not registered on element level by default as this namespace isn't registered manually, instead it's a "magic" namespace. This also ensures we match the behaviour of libxml more closely, hopefully reducing confusion. --- lib/oga.rb | 2 +- lib/oga/xml/attribute.rb | 21 ++++++++++++++++++++- spec/oga/xml/attribute_spec.rb | 6 ++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/oga.rb b/lib/oga.rb index 5bc0e6a..83537c7 100644 --- a/lib/oga.rb +++ b/lib/oga.rb @@ -25,8 +25,8 @@ require_relative 'oga/xml/cdata' require_relative 'oga/xml/xml_declaration' require_relative 'oga/xml/processing_instruction' require_relative 'oga/xml/doctype' -require_relative 'oga/xml/attribute' require_relative 'oga/xml/namespace' +require_relative 'oga/xml/attribute' require_relative 'oga/xml/element' require_relative 'oga/xml/node_set' diff --git a/lib/oga/xml/attribute.rb b/lib/oga/xml/attribute.rb index 1acefb2..7f0c99f 100644 --- a/lib/oga/xml/attribute.rb +++ b/lib/oga/xml/attribute.rb @@ -21,6 +21,17 @@ module Oga class Attribute attr_accessor :name, :namespace_name, :element, :value + ## + # The default namespace available to all attributes. This namespace can + # not be modified. + # + # @return [Oga::XML::Namespace] + # + DEFAULT_NAMESPACE = Namespace.new( + :name => 'xml', + :uri => 'http://www.w3.org/XML/1998/namespace' + ).freeze + ## # @param [Hash] options # @@ -44,7 +55,15 @@ module Oga # @return [Oga::XML::Namespace] # def namespace - return @namespace ||= element.available_namespaces[namespace_name] + unless @namespace + if namespace_name == DEFAULT_NAMESPACE.name + @namespace = DEFAULT_NAMESPACE + else + @namespace = element.available_namespaces[namespace_name] + end + end + + return @namespace end ## diff --git a/spec/oga/xml/attribute_spec.rb b/spec/oga/xml/attribute_spec.rb index be08cf7..8d9bdb0 100644 --- a/spec/oga/xml/attribute_spec.rb +++ b/spec/oga/xml/attribute_spec.rb @@ -24,11 +24,17 @@ describe Oga::XML::Attribute do :name => 'a', :element => element ) + + @default = described_class.new(:namespace_name => 'xml', :name => 'x') end example 'return a Namespace instance' do @attribute.namespace.should == @namespace end + + example 'return the default XML namespace when the "xml" prefix is used' do + @default.namespace.should == Oga::XML::Attribute::DEFAULT_NAMESPACE + end end context '#to_s' do