From d40baf0c724a3874f43100fbefa775cfb8dcacda Mon Sep 17 00:00:00 2001 From: Scott Wheeler Date: Mon, 12 Sep 2016 13:05:02 +0300 Subject: [PATCH] Add aliases for accessing attributes via [] and []= This also fixes accessing attributes via symbol name and tests to ensure that such does not break in the future. --- lib/oga/xml/element.rb | 10 +++++----- spec/oga/xml/element_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index a2732d1..d04c2cf 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -91,6 +91,8 @@ module Oga found ? found.value : nil end + alias_method :[], :get + # Adds a new attribute to the element. # # @param [Oga::XML::Attribute] attribute @@ -113,11 +115,7 @@ module Oga if found found.value = value else - if name.include?(':') - ns, name = name.split(':') - else - ns = nil - end + name, ns = split_name(name) attr = Attribute.new( :name => name, @@ -129,6 +127,8 @@ module Oga end end + alias_method :[]=, :set + # Removes an attribute from the element. # # @param [String] name The name (optionally including namespace prefix) diff --git a/spec/oga/xml/element_spec.rb b/spec/oga/xml/element_spec.rb index 9bfd17f..89c5e6b 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -129,6 +129,13 @@ describe Oga::XML::Element do end end + describe '#[]' do + it 'is an alias to get' do + described_class.instance_method(:[]).should == + described_class.instance_method(:get) + end + end + describe '#add_attribute' do before do @element = described_class.new @@ -161,6 +168,14 @@ describe Oga::XML::Element do @element.get('class').should == 'foo' end + it 'supports the use of Symbols for attribute names' do + @element.set(:foo, 'foo') + @element.get('foo').should == 'foo' + + @element.set('bar', 'bar') + @element.get(:bar).should == 'bar' + end + it 'adds a new attribute with a namespace' do @element.set('x:bar', 'foo') @@ -186,6 +201,13 @@ describe Oga::XML::Element do end end + describe '#[]=' do + it 'is an alias to set' do + described_class.instance_method(:[]=).should == + described_class.instance_method(:set) + end + end + describe '#unset' do before do @element = described_class.new