dnb_core_ext

Extensions to Ruby String and Hash methods packaged into a plugin

ToProperClass

Extensions to Hash, Array and String


HASH METHODS

Hash.values_to_proper_class
Note: this method relies upon the string methods below

This takes a hash with keys that are either strings or symbols and values that are either strings or hashes.

It iterates through the hash and converts all keys to :symbols and all values to their appropriate class value (Integer, Float, String, TrueClass, FalseClass)

This allows you to take a bunch of POST data that has converted all of your numbers, true, false, etc. to strings and turn it back into the appropriate classed value.

example

test_hash = {
:pet => ‘dog’,
:name => ‘Fido’,
:state => ‘Indiana’,
‘is_trained?’ => ‘false’,
‘is_old?’ => ‘true’,
‘how_old?’ => ‘7’,
‘some_num’ => ‘4.355’,
‘extras’ => {
:usage => ‘document’,
‘town’ => ‘Indianapolis’,
‘pi’ => ‘3.14’,
:new_record => ‘true’,
‘other_stuff’ => {
‘color’ => ‘brown’,
:vehicle => ‘truck’,
‘year’ => ‘1942’,
‘another_decimal’ => ‘9.81’,
:good => ‘true’
}
}
}

puts test_hash.classed_values.inspect

OUTPUT
{ :some_num=>4.355, :extras=>{ :new_record=>true, :usage=>“document”, :pi=>3.14, :town=>“Indianapolis”, :other_stuff=>{:good?=>true, :vehicle=>“truck”, :another_decimal=>9.81, :color=>“brown”, :year=>1942}}, :name=>“Fido”, :pet=>“dog”, :is_old?=>true, :state=>“Indiana”, :how_old?=>7, :is_trained?=>false }


STRING METHODS

String.integer?
Returns boolean value of whether the given string represents an integer.
‘27’.integer? = true
‘27.3’.integer? = false
‘dog’.integer? = false

String.float?
Returns boolean value of whether the given string represents a float.
‘27’.float? = false
‘27.3’.float? = true
‘dog’.float? = false

String.boolean?
Returns boolean value of whether the given string represents a boolean value.
‘false’.boolean? = true
‘true’.boolean? = true
‘dog’.boolean? = false


Copyright © 2008 David Baldwin (github.com/bilson), Elijah Miller (github.com/jqr) & Kristopher Chambers (github.com/kristopher), released under the MIT license