diff options
author | Michael Bleigh <mbleigh@mbleigh.com> | 2014-04-11 21:38:26 +0000 |
---|---|---|
committer | Michael Bleigh <mbleigh@mbleigh.com> | 2014-04-11 21:38:26 +0000 |
commit | 3e9443df3235f619cdbbc0e7fad113f00ed240bf (patch) | |
tree | 4794b53ded1da179cf3d6c46823ff4136556a7e7 | |
parent | 1dc31fdf07b7864ddb17aad64804ea32e1dd1341 (diff) | |
download | hashie-3e9443df3235f619cdbbc0e7fad113f00ed240bf.tar.gz |
Check arity of #to_hash before calling. Closes #144
-rw-r--r-- | lib/hashie/hash.rb | 16 | ||||
-rw-r--r-- | spec/hashie/hash_spec.rb | 12 |
2 files changed, 25 insertions, 3 deletions
diff --git a/lib/hashie/hash.rb b/lib/hashie/hash.rb index 0916135..2304872 100644 --- a/lib/hashie/hash.rb +++ b/lib/hashie/hash.rb @@ -16,18 +16,28 @@ module Hashie if self[k].is_a?(Array) out[assignment_key] ||= [] self[k].each do |array_object| - out[assignment_key] << (Hash === array_object ? array_object.to_hash(options) : array_object) + out[assignment_key] << (Hash === array_object ? flexibly_convert_to_hash(array_object, options) : array_object) end else - out[assignment_key] = Hash === self[k] ? self[k].to_hash(options) : self[k] + out[assignment_key] = Hash === self[k] ? flexibly_convert_to_hash(self[k], options) : self[k] end end out end - # The C geneartor for the json gem doesn't like mashies + # The C generator for the json gem doesn't like mashies def to_json(*args) to_hash.to_json(*args) end + + private + + def flexibly_convert_to_hash(object, options = {}) + if object.method(:to_hash).arity == 0 + object.to_hash + else + object.to_hash(options) + end + end end end diff --git a/spec/hashie/hash_spec.rb b/spec/hashie/hash_spec.rb index df1e557..ad92191 100644 --- a/spec/hashie/hash_spec.rb +++ b/spec/hashie/hash_spec.rb @@ -31,4 +31,16 @@ describe Hash do symbolized_hash = hash.to_hash(symbolize_keys: true) expect(symbolized_hash).to eq(:a => 'hey', :"123" => 'bob', :array => [1, 2, 3]) end + + it "#to_hash should not blow up when #to_hash doesn't accept arguments" do + class BareCustomMash < Hashie::Mash + def to_hash + {} + end + end + + h = Hashie::Hash.new + h[:key] = BareCustomMash.new + expect{ h.to_hash }.not_to raise_error + end end |