Skip to content

Commit 3d640b8

Browse files
committed
Added a safety guard for double wrapping.
Signed-off-by: Hermann Mayer <hermann.mayer92@gmail.com>
1 parent c38a884 commit 3d640b8

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

lib/recursive_open_struct.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ def self.default_options
2929
end
3030

3131
def initialize(hash=nil, passed_options={})
32+
hash = hash.to_h if [hash.is_a?(RecursiveOpenStruct), hash.is_a?(OpenStruct)].any?
3233
hash ||= {}
3334

3435
@options = self.class.default_options.merge!(passed_options).freeze
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
require_relative '../spec_helper'
2+
require 'recursive_open_struct'
3+
4+
describe RecursiveOpenStruct do
5+
describe 'wrapping RecursiveOpenStruct' do
6+
let(:h) { { :blah => { :another => 'value' } } }
7+
subject(:ros) { RecursiveOpenStruct.new(RecursiveOpenStruct.new(h)) }
8+
9+
it 'can convert the entire hash tree back into a hash' do
10+
expect(ros.to_h).to eq h
11+
end
12+
13+
it 'can access the flat keys' do
14+
expect(ros.blah).to be_a(RecursiveOpenStruct)
15+
end
16+
17+
it 'can access the nested keys' do
18+
expect(ros.blah.another).to eql('value')
19+
end
20+
21+
it 'can be inspected' do
22+
expect(ros.inspect).to \
23+
eql('#<RecursiveOpenStruct blah={another: "value"}>')
24+
end
25+
end
26+
27+
describe 'wrapping OpenStruct' do
28+
let(:h) { { :blah => { :another => 'value' } } }
29+
subject(:ros) { RecursiveOpenStruct.new(OpenStruct.new(h)) }
30+
31+
it 'can convert the entire hash tree back into a hash' do
32+
expect(ros.to_h).to eq h
33+
end
34+
35+
it 'can access the flat keys' do
36+
expect(ros.blah).to be_a(RecursiveOpenStruct)
37+
end
38+
39+
it 'can access the nested keys' do
40+
expect(ros.blah.another).to eql('value')
41+
end
42+
43+
it 'can be inspected' do
44+
expect(ros.inspect).to \
45+
eql('#<RecursiveOpenStruct blah={another: "value"}>')
46+
end
47+
end
48+
49+
describe 'wrapping a subclass' do
50+
let(:h) { { :blah => { :another => 'value' } } }
51+
let(:subclass) { Class.new(RecursiveOpenStruct) }
52+
subject(:ros) { subclass.new(subclass.new(h)) }
53+
54+
it 'can convert the entire hash tree back into a hash' do
55+
expect(ros.to_h).to eq h
56+
end
57+
58+
it 'can access the flat keys' do
59+
expect(ros.blah).to be_a(RecursiveOpenStruct)
60+
end
61+
62+
it 'can access the nested keys' do
63+
expect(ros.blah.another).to eql('value')
64+
end
65+
66+
it 'can be inspected' do
67+
expect(ros.inspect).to \
68+
end_with(' blah={another: "value"}>')
69+
end
70+
end
71+
end

0 commit comments

Comments
 (0)