From 9650f4bb035b8abba07a8bdf066ebc933f3593e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=85=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=94=D0=BC?= =?UTF-8?q?=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Wed, 30 Aug 2023 19:46:05 +0200 Subject: [PATCH] Add option "string_with_attributes_as_hash" to transform simple tags with attributes to hash instead of StringWithAttributes class --- lib/nori.rb | 19 ++++++++++--------- lib/nori/xml_utility_node.rb | 8 ++++++-- spec/nori/nori_spec.rb | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/lib/nori.rb b/lib/nori.rb index ba55215..db3e51f 100644 --- a/lib/nori.rb +++ b/lib/nori.rb @@ -15,15 +15,16 @@ def self.hash_key(name, options = {}) def initialize(options = {}) defaults = { - :strip_namespaces => false, - :delete_namespace_attributes => false, - :convert_tags_to => nil, - :convert_attributes_to => nil, - :empty_tag_value => nil, - :advanced_typecasting => true, - :convert_dashes_to_underscores => true, - :scrub_xml => true, - :parser => :nokogiri + :strip_namespaces => false, + :delete_namespace_attributes => false, + :convert_tags_to => nil, + :convert_attributes_to => nil, + :empty_tag_value => nil, + :advanced_typecasting => true, + :convert_dashes_to_underscores => true, + :scrub_xml => true, + :parser => :nokogiri, + :string_with_attributes_as_hash => false, } validate_options! defaults.keys, options.keys diff --git a/lib/nori/xml_utility_node.rb b/lib/nori/xml_utility_node.rb index 63d74a4..c471025 100644 --- a/lib/nori/xml_utility_node.rb +++ b/lib/nori/xml_utility_node.rb @@ -140,8 +140,12 @@ def to_hash t = advanced_typecasting(t) if t.is_a?(String) && @options[:advanced_typecasting] if t.is_a?(String) - t = StringWithAttributes.new(t) - t.attributes = attributes + if @options[:string_with_attributes_as_hash] && attributes.any? + t = { '#text' => t }.merge(attributes.transform_keys { |k| "@#{k}" }) + else + t = StringWithAttributes.new(t) + t.attributes = attributes + end end return { name => t } diff --git a/spec/nori/nori_spec.rb b/spec/nori/nori_spec.rb index e673722..1db3ea4 100644 --- a/spec/nori/nori_spec.rb +++ b/spec/nori/nori_spec.rb @@ -231,6 +231,20 @@ expect("some-string").not_to respond_to(:attributes) expect("some-string").not_to respond_to(:attributes=) end + + it "returns hash with :string_with_attributes_as_hash option" do + xml =<<-XML + + Text + Gary R Epstein + Simon T Tyson + + XML + @data = parse(xml, { string_with_attributes_as_hash: true }) + expect(@data['opt']['test']).to eq({ '#text' => 'Text', '@attr' => 'value', '@attr1' => 'value1' }) + expect(@data['opt']['user'][0]).to eq({ '#text' => 'Gary R Epstein', '@login' => 'grep' }) + expect(@data['opt']['user'][1]).to eq('Simon T Tyson') + end end it "should typecast an integer" do