diff --git a/lib/recursive_open_struct.rb b/lib/recursive_open_struct.rb index 9e435fe..a0d01ea 100644 --- a/lib/recursive_open_struct.rb +++ b/lib/recursive_open_struct.rb @@ -29,6 +29,7 @@ def self.default_options end def initialize(hash=nil, passed_options={}) + hash = hash.to_h if [hash.is_a?(RecursiveOpenStruct), hash.is_a?(OpenStruct)].any? hash ||= {} @options = self.class.default_options.merge!(passed_options).freeze diff --git a/spec/recursive_open_struct/wrapping_spec.rb b/spec/recursive_open_struct/wrapping_spec.rb new file mode 100644 index 0000000..7a6f2e4 --- /dev/null +++ b/spec/recursive_open_struct/wrapping_spec.rb @@ -0,0 +1,70 @@ +require_relative '../spec_helper' +require 'recursive_open_struct' + +describe RecursiveOpenStruct do + describe 'wrapping RecursiveOpenStruct' do + let(:h) { { :blah => { :another => 'value' } } } + subject(:ros) { RecursiveOpenStruct.new(RecursiveOpenStruct.new(h)) } + + it 'can convert the entire hash tree back into a hash' do + expect(ros.to_h).to eq h + end + + it 'can access the flat keys' do + expect(ros.blah).to be_a(RecursiveOpenStruct) + end + + it 'can access the nested keys' do + expect(ros.blah.another).to eql('value') + end + + it 'can be inspected' do + expect(ros.inspect).to \ + match(/#)"value"}>/) + end + end + + describe 'wrapping OpenStruct' do + let(:h) { { :blah => { :another => 'value' } } } + subject(:ros) { RecursiveOpenStruct.new(OpenStruct.new(h)) } + + it 'can convert the entire hash tree back into a hash' do + expect(ros.to_h).to eq h + end + + it 'can access the flat keys' do + expect(ros.blah).to be_a(RecursiveOpenStruct) + end + + it 'can access the nested keys' do + expect(ros.blah.another).to eql('value') + end + + it 'can be inspected' do + expect(ros.inspect).to \ + match(/#)"value"}>/) + end + end + + describe 'wrapping a subclass' do + let(:h) { { :blah => { :another => 'value' } } } + let(:subclass) { Class.new(RecursiveOpenStruct) } + subject(:ros) { subclass.new(subclass.new(h)) } + + it 'can convert the entire hash tree back into a hash' do + expect(ros.to_h).to eq h + end + + it 'can access the flat keys' do + expect(ros.blah).to be_a(RecursiveOpenStruct) + end + + it 'can access the nested keys' do + expect(ros.blah.another).to eql('value') + end + + it 'can be inspected' do + expect(ros.inspect).to match(/ blah={:?another(: |=>)"value"}>$/) + end + end +end