Class: Hash

Inherits:
Object show all
Defined in:
lib/qualitysmith_extensions/hash/to_date.rb,
lib/qualitysmith_extensions/hash/to_query_string.rb

Instance Method Summary collapse

Instance Method Details

#to_dateObject

Converts a {:year => ..., :month => ..., :day => ...} hash into an actual Date object. Useful for when you have a date element in your params hash.



14
15
16
# File 'lib/qualitysmith_extensions/hash/to_date.rb', line 14

def to_date
  Date.new(fetch(:year).to_i, fetch(:month).to_i, fetch(:day).to_i)
end

#to_query_string(key = '') ⇒ Object

Converts into a string that can be used as the query string of a URL (for example, ?key1=val1&key2=val2).

Example:
  {
    'colors' => ['red', 'blue'],
    'username' => 'pineapple'
  }.to_query_string('data')
  ==> "data[username]=pineapple&data[colors][]=red&data[colors][]=blue"

The hash can be nested as deeply as you want and can also contain arrays.

<tt>key</tt> is the name of the key in params that will receive this hash when you load the page. So, for example, if you go to page with this query string (key = "name"): <tt>?name[first]=Fred&name[last]=Fredson</tt>, params will be have a key "name", like so: <tt>{"name"=>{"last"=>"Fredson", "first"=>"Fred"}}</tt>.

  {
    'colors' => ['red', 'blue'],
    'username' => 'pineapple'
  }.to_query_string('data')

is equivalent to just writing your hash like so:

  {
    'data' => {
      'colors' => ['red', 'blue'],
      'username' => 'pineapple'
    }
  }.to_query_string()


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/qualitysmith_extensions/hash/to_query_string.rb', line 43

def to_query_string(key = '')
  prefix = key.dup
  elements = []

  self.each_pair do |key, value|
    key = CGI.escape key.to_s
    key = prefix.length > 1 ? "#{prefix}[#{key}]" : key
    if value.respond_to? :to_query_string
      valuepre = value.dup
      value = value.to_query_string(key)
      #puts "#{key}#{valuepre.inspect} => #{value}"
      elements << value
    else
      value = CGI.escape value.to_s
      elements << key + '=' + value
    end
  end

  elements.join('&')
end