diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 67ba043..e60abc6 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -73,7 +73,6 @@ # of these properties compared to using a Hash or a Struct. # class OpenStruct - # # Creates a new OpenStruct object. By default, the resulting OpenStruct # object will have no attributes. @@ -88,12 +87,14 @@ class OpenStruct # # data # => # # - def initialize(hash=nil) + def initialize(hash=nil, options={recursive: true}) @table = {} + @recursive = options.fetch(:recursive, false) + puts @recursive if hash hash.each_pair do |k, v| k = k.to_sym - @table[k] = v + @table[k] = (@recursive && v.respond_to?(:to_hash)) ? OpenStruct.new(v, {recursive: true}) : v end end end @@ -202,7 +203,7 @@ def method_missing(mid, *args) # :nodoc: if len != 1 raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1) end - modifiable?[new_ostruct_member!(mname)] = args[0] + modifiable?[new_ostruct_member!(mname)] = (@recursive && args[0].respond_to?(:to_hash)) ? OpenStruct.new(args[0], {recursive: true}) : args[0] elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid # if @table.key?(mid) new_ostruct_member!(mid) unless frozen?