From ee4690d08ecf02919932aad57b20bef77ba4edaa Mon Sep 17 00:00:00 2001 From: Ben Linsay Date: Fri, 11 Sep 2015 10:57:04 -0400 Subject: [PATCH] add a recursive_to_h method making to_h recursive by default breaks #with in an important way. return to_h to it's old self and add recursive_to_h. --- lib/values.rb | 12 ++++++++---- spec/values_spec.rb | 8 +++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/values.rb b/lib/values.rb index 4f341ee..b6a48d1 100644 --- a/lib/values.rb +++ b/lib/values.rb @@ -74,7 +74,11 @@ def with(hash = {}) end def to_h - Hash[to_a.map{|k, v| [k, Value.try_to_h(v)]}] + Hash[to_a] + end + + def recursive_to_h + Hash[to_a.map{|k, v| [k, Value.coerce_to_h(v)]}] end def to_a @@ -87,12 +91,12 @@ def to_a protected - def self.try_to_h(v) + def self.coerce_to_h(v) case when v.is_a?(Hash) - Hash[v.map{|hk, hv| [hk, try_to_h(hv)]}] + Hash[v.map{|hk, hv| [hk, coerce_to_h(hv)]}] when v.respond_to?(:map) - v.map{|x| try_to_h(x)} + v.map{|x| coerce_to_h(x)} when v && v.respond_to?(:to_h) v.to_h else diff --git a/spec/values_spec.rb b/spec/values_spec.rb index 6091ad7..6c13475 100644 --- a/spec/values_spec.rb +++ b/spec/values_spec.rb @@ -193,17 +193,19 @@ def change_color(new_color) it 'returns a hash of fields and values' do expect(Point.new(1, -1).to_h).to eq({ :x => 1, :y => -1 }) end + end + describe '#recursive_to_h' do it 'converts nested values' do - expect(Rectangle.new(Point.new(0, 1), Point.new(1, 0)).to_h).to eq({:top_left => {:x => 0, :y => 1}, :bottom_right => {:x => 1, :y => 0}}) + expect(Rectangle.new(Point.new(0, 1), Point.new(1, 0)).recursive_to_h).to eq({:top_left => {:x => 0, :y => 1}, :bottom_right => {:x => 1, :y => 0}}) end it 'converts values in an array field' do - expect(Board.new([Cell.new(false), Cell.new(true)]).to_h).to eq({:cells => [{:alive => false}, {:alive => true}]}) + expect(Board.new([Cell.new(false), Cell.new(true)]).recursive_to_h).to eq({:cells => [{:alive => false}, {:alive => true}]}) end it 'converts values in a hash field' do - expect(Board.new({:mine => Cell.new(true), :yours => Cell.new(false)}).to_h).to eq({:cells => {:mine => {:alive => true}, :yours => {:alive => false}}}) + expect(Board.new({:mine => Cell.new(true), :yours => Cell.new(false)}).recursive_to_h).to eq({:cells => {:mine => {:alive => true}, :yours => {:alive => false}}}) end end