require 'spec_helper'

describe Hash do

  describe '#deep_slice' do

    it 'should return a sub-hash that only contains the given keys' do
      { :a => 'a', :b => 'b', :c => 'c' }.deep_slice(:a, :c).should == { :a => 'a', :c => 'c' }
    end

    it 'should allow to recursively slice hashes of hashes' do
      cow = {
        :a => 'a',
        :b => 'b',
        :c => {
          :d => {
            :e => 'e',
            :f => 'f'
          },
          :g => {
            :h => 'h',
            :i => 'i'
          }
        }
      }
      knife = [
        :a, {
          :c => {
            :d => :f,
            :g => [:h, :i]
          }
        }
      ]
      steak = {
        :a => 'a',
        :c => {
          :d => {
            :f => 'f'
          },
          :g => {
            :h => 'h',
            :i => 'i'
          }
        }
      }
      cow.deep_slice(*knife).should == steak
    end

    it 'should raise an ArgumentError if the value for a given key is not a Hash' do
      expect do
        { :a => 'a', :b => 'b' }.deep_slice(:a => :x)
      end.to raise_error(ArgumentError)
    end

    it 'should ignore if a nested subkey does not exist in the receiver' do
      nested_hash = { :a => { :b => 'b' } }
      nested_hash.deep_slice(:a => :x).should == { :a => {} }
    end

    it 'should allow to recursively slice multiple subhashes on the same depth' do
      cow = {
        :a => {
          :b => 'b',
          :c => 'c'
        },
        :d => {
          :e => 'e',
          :f => 'f'
        }
      }
      knife = {
        :a => :c,
        :d => :e
      }
      steak = {
        :a => {
          :c => 'c'
        },
        :d => {
          :e => 'e'
        }
      }
      cow.deep_slice(knife).should == steak
    end

  end

end
