Class | Hash |
In: |
lib/extlib/hash.rb
|
Parent: | Object |
Converts valid XML into a Ruby Hash structure.
Mixed content is treated as text and any tags in it are left unparsed
Any attributes other than type on a node containing a text node will be discarded
boolean: | Anything other than "true" evaluates to false. |
datetime: | Returns a Time object. See Time documentation for valid Time strings. |
date: | Returns a Date object. See Date documentation for valid Date strings. |
Keys are automatically converted to snake_case
[Simple]
<user gender='m'> <age type='integer'>35</age> <name>Home Simpson</name> <dob type='date'>1988-01-01</dob> <joined-at type='datetime'>2000-04-28 23:01</joined-at> <is-cool type='boolean'>true</is-cool> </user>
Becomes:
{ "user" => { "gender" => "m", "age" => 35, "name" => "Home Simpson", "dob" => DateObject( 1998-01-01 ), "joined_at" => TimeObject( 2000-04-28 23:01), "is_cool" => true } }
[Mixed Content]
<story> A Quick <em>brown</em> Fox </story>
Evaluates to:
{ "story" => "A Quick <em>brown</em> Fox" }
[Attributes other than type on a node containing text]
<story is-good='false'> A Quick <em>brown</em> Fox </story>
Are ignored:
{ "story" => "A Quick <em>brown</em> Fox" }
[Other attributes in addition to type]
<bicep unit='inches' type='integer'>60</bicep>
Evaluates with a typecast to an integer. But unit attribute is ignored:
{ "bicep" => 60 }
@param [String] xml A string representation of valid XML.
@return [Hash] A hash created by parsing xml
# File lib/extlib/hash.rb, line 73 73: def from_xml( xml ) 74: ToHashParser.from_xml(xml) 75: end
@param html_class<to_s>
The HTML class to add to the :class key. The html_class will be concatenated to any existing classes.
@example hash[:class] #=> nil @example hash.add_html_class!(:selected) @example hash[:class] #=> "selected" @example hash.add_html_class!("class1 class2") @example hash[:class] #=> "selected class1 class2"
# File lib/extlib/hash.rb, line 201 201: def add_html_class!(html_class) 202: if self[:class] 203: self[:class] = "#{self[:class]} #{html_class}" 204: else 205: self[:class] = html_class.to_s 206: end 207: end
Destructively and non-recursively convert each key to an uppercase string, deleting nil values along the way.
@return <Hash> The newly environmentized hash.
@example
{ :name => "Bob", :contact => { :email => "bob@bob.com" } }.environmentize_keys! #=> { "NAME" => "Bob", "CONTACT" => { :email => "bob@bob.com" } }
# File lib/extlib/hash.rb, line 242 242: def environmentize_keys! 243: keys.each do |key| 244: val = delete(key) 245: next if val.nil? 246: self[key.to_s.upcase] = val 247: end 248: self 249: end
Create a hash with all key/value pairs in receiver except rejected
{ :one => 1, :two => 2, :three => 3 }.except(:one) #=> { :two => 2, :three => 3 }
@param [Array[String, Symbol]] *rejected The hash keys to exclude.
@return [Hash] A new hash without the selected keys.
@api public
# File lib/extlib/hash.rb, line 173 173: def except(*rejected) 174: hash = self.dup 175: rejected.each {|k| hash.delete(k) } 176: hash 177: end
Convert a key, value pair into a URL query param string
normalize_param(:name, "Bob") #=> "name=Bob&"
@param [Object] key The key for the param. @param [Object] value The value for the param.
@return <String> This key value pair as a param
@api public
# File lib/extlib/hash.rb, line 121 121: def normalize_param(key, value) 122: param = '' 123: stack = [] 124: 125: if value.is_a?(Array) 126: param << value.map { |element| normalize_param("#{key}[]", element) }.join 127: elsif value.is_a?(Hash) 128: stack << [key,value] 129: else 130: param << "#{key}=#{value}&" 131: end 132: 133: stack.each do |parent, hash| 134: hash.each do |k, v| 135: if v.is_a?(Hash) 136: stack << ["#{parent}[#{k}]", v] 137: else 138: param << normalize_param("#{parent}[#{k}]", v) 139: end 140: end 141: end 142: 143: param 144: end
Create a hash with only key/value pairs in receiver and allowed
{ :one => 1, :two => 2, :three => 3 }.only(:one) #=> { :one => 1 }
@param [Array[String, Symbol]] *allowed The hash keys to include.
@return [Hash] A new hash with only the selected keys.
@api public
# File lib/extlib/hash.rb, line 156 156: def only(*allowed) 157: hash = {} 158: allowed.each {|k| hash[k] = self[k] if self.has_key?(k) } 159: hash 160: end
Converts all keys into string values. This is used during reloading to prevent problems when classes are no longer declared.
@return <Array> An array of they hash‘s keys
@example
hash = { One => 1, Two => 2 }.proctect_keys! hash # => { "One" => 1, "Two" => 2 }
# File lib/extlib/hash.rb, line 217 217: def protect_keys! 218: keys.each {|key| self[key.to_s] = delete(key) } 219: end
Convert to Mash. This class has semantics of ActiveSupport‘s HashWithIndifferentAccess and we only have it so that people can write params[:key] instead of params[‘key’].
@return [Mash] This hash as a Mash for string or symbol key access.
# File lib/extlib/hash.rb, line 83 83: def to_mash 84: hash = Mash.new(self) 85: hash.default = default 86: hash 87: end
Convert to URL query param string
{ :name => "Bob", :address => { :street => '111 Ruby Ave.', :city => 'Ruby Central', :phones => ['111-111-1111', '222-222-2222'] } }.to_params #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave."
@return [String] This hash as a query string
@api public
# File lib/extlib/hash.rb, line 104 104: def to_params 105: params = self.map { |k,v| normalize_param(k,v) }.join 106: params.chop! # trailing & 107: params 108: end
@return <String> The hash as attributes for an XML tag.
@example
{ :one => 1, "two"=>"TWO" }.to_xml_attributes #=> 'one="1" two="TWO"'
# File lib/extlib/hash.rb, line 184 184: def to_xml_attributes 185: map do |k,v| 186: %{#{k.to_s.snake_case.sub(/^(.{1,1})/) { |m| m.downcase }}="#{v}"} 187: end.join(' ') 188: end
Attempts to convert all string keys into Class keys. We run this after reloading to convert protected hashes back into usable hashes.
@example
# Provided that classes One and Two are declared in this scope: hash = { "One" => 1, "Two" => 2 }.unproctect_keys! hash # => { One => 1, Two => 2 }
# File lib/extlib/hash.rb, line 228 228: def unprotect_keys! 229: keys.each do |key| 230: (self[Object.full_const_get(key)] = delete(key)) rescue nil 231: end 232: end