Class: Hash

Inherits:
Object show all
Defined in:
lib/quality_extensions/hash/only.rb,
lib/quality_extensions/hash/to_date.rb,
lib/quality_extensions/hash/hash_select.rb,
lib/quality_extensions/hash/delete_unless.rb,
lib/quality_extensions/hash/to_query_string.rb,
lib/quality_extensions/hash/assert_has_only_keys.rb

Overview

– Source: pastie.org/10707 (08/29/2006 by lukeredpath)

Author

Unknown, Tyler Rick

Copyright

Unknown, Tyler Rick

License

Original: assumed public domain / Modified version: Ruby License

Submit to Facets?

No. Already in Facets (different implementation).

Developer notes
Changes

++

Instance Method Summary collapse

Instance Method Details

#assert_has_only_keys(*check_keys) ⇒ Object

Returns true is hash has only then given keys, otherwise throws an ArgumentError.

h = { :a => 1, :b => 2 }
h.assert_has_only_keys( :a, :b )   #=> true
h.assert_has_only_keys( :a )       #=> ArgumentError

Raises:

  • (ArgumentError)


21
22
23
# File 'lib/quality_extensions/hash/assert_has_only_keys.rb', line 21

def assert_has_only_keys(*check_keys)
  raise(ArgumentError, "has unexpected key(s)") unless has_only_keys?(*check_keys)
end

#except(*keys) ⇒ Object

Returns the hash with the keys named by keys having been removed.

{:a => 1, :b => 2, :c => 3}.except(:a)

> => 2, :c => 3



16
17
18
19
20
# File 'lib/quality_extensions/hash/only.rb', line 16

def except(*keys)
  self.reject { |k,v|
    keys.include? k
  }
end

#hash_select(&block) ⇒ Object Also known as: hash_find_all, delete_unless

call-seq:

hash.hash_select {| key, value | block }  -> hash

Hash#reject returns a hash. One would intuitively expect Hash#select to also return a hash. However, it doesn’t: instead, returns “a new array consisting of [key,value] pairs for which the block returns true”.

Hash#hash_select behaves how Hash#select (arguably) should behave: Deletes every key-value pair from a copy of hash except those for which block evaluates to true.



20
21
22
23
24
# File 'lib/quality_extensions/hash/hash_select.rb', line 20

def hash_select(&block)
  reject {|k, v|
    !yield k, v
  }
end

#only(*keys) ⇒ Object

Returns the hash with only the keys named by keys having been kept.

{:a => 1, :b => 2, :c => 3}.only(:a)

> => 1



26
27
28
29
30
# File 'lib/quality_extensions/hash/only.rb', line 26

def only(*keys)
  self.dup.reject { |k,v|
    !keys.include? k
  }
end

#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/quality_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()


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

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