Skip to content

Commit

Permalink
add a recursive_to_h method
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Ben Linsay committed Sep 11, 2015
1 parent 8e3a1a1 commit ee4690d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
12 changes: 8 additions & 4 deletions lib/values.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down
8 changes: 5 additions & 3 deletions spec/values_spec.rb
Expand Up @@ -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

Expand Down

0 comments on commit ee4690d

Please sign in to comment.