Skip to content

Commit c86ced5

Browse files
committed
Make recursiveness optional. Default is set to false.
1 parent 252ff50 commit c86ced5

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

lib/ostruct.rb

+5-3
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
# of these properties compared to using a Hash or a Struct.
7474
#
7575
class OpenStruct
76+
attr_reader :recursive
7677

7778
#
7879
# Creates a new OpenStruct object. By default, the resulting OpenStruct
@@ -88,12 +89,13 @@ class OpenStruct
8889
#
8990
# data # => #<OpenStruct country="Australia", capital="Canberra">
9091
#
91-
def initialize(hash=nil)
92+
def initialize(hash=nil, recursive=false)
9293
@table = {}
94+
@recursive = recursive
9395
if hash
9496
hash.each_pair do |k, v|
9597
k = k.to_sym
96-
@table[k] = v.is_a?(Hash) ? OpenStruct.new(v) : v
98+
@table[k] = (recursive && v.is_a?(Hash)) ? OpenStruct.new(v, recursive: true) : v
9799
end
98100
end
99101
end
@@ -202,7 +204,7 @@ def method_missing(mid, *args) # :nodoc:
202204
if len != 1
203205
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
204206
end
205-
modifiable?[new_ostruct_member!(mname)] = args[0].is_a?(Hash) ? OpenStruct.new(args[0]) : args[0]
207+
modifiable?[new_ostruct_member!(mname)] = (recursive && args[0].is_a?(Hash)) ? OpenStruct.new(args[0], recursive: true) : args[0]
206208
elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid #
207209
if @table.key?(mid)
208210
new_ostruct_member!(mid) unless frozen?

0 commit comments

Comments
 (0)