Technical
Validate Nested Keys

This stub was originaly developed by Mike Park.

It helps you to check your nested keys.

for example when you have


<%= text_field :person,:name %>

your params would look like params[:person][:name]
:name would be nested key and just using params[:person].has_key? :name will not see it.

You can put this code in to yout appliocation controller helper to be available to every controller in your app.


\<your app>/app/controllers/application.rb 

Thanks Mike



#!/usr/bin/env ruby

require 'test/unit'

class Hash
  def nested_key?(target)
   each_value do |value|
    return true if value.has_key? target
   end
   false
  end
end

class TestHash < Test::Unit::TestCase

  def test_nested_key?
   params = {"parent" => {"name" => "foo"}}
   assert_equal( true, params.nested_key?("name") )
   assert_equal( false, params.nested_key?("dog") )
  end

  def test_key_value
   params = {"parent" => {"name" => "foo"}}
   assert_equal( true, params.value?({"name" => "foo"}) )
   assert_equal( false, params.value?({"dog" => "cat"}) )
  end

end