Skip to content

Recursively converting child hash attributes to OpenStruct. #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions lib/ostruct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -88,12 +87,14 @@ class OpenStruct
#
# data # => #<OpenStruct country="Australia", capital="Canberra">
#
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
Expand Down Expand Up @@ -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?
Expand Down