class Hash
Public Instance Methods
convert_date(date_symbol_or_string)
click to toggle source
takes a Hash
(like the params hash), and converts the Rails date attributes to a real Date
object. {'start_date(1i)' => 2012, 'start_date(2i)' => 11, 'start_date(3i)' => 23}.convert_date(:start_date)
# File lib/dm_ruby_extensions/extend_hash.rb, line 8 def convert_date(date_symbol_or_string) attribute = date_symbol_or_string.to_s return nil if self[attribute + '(1i)'].nil? || self[attribute + '(2i)'].nil? || self[attribute + '(3i)'].nil? return Date.new(self[attribute + '(1i)'].to_i, self[attribute + '(2i)'].to_i, self[attribute + '(3i)'].to_i) end
convert_datetime(date_symbol_or_string)
click to toggle source
takes a Hash
(like the params hash), and converts the Rails datetime attributes to a real Date
object.
# File lib/dm_ruby_extensions/extend_hash.rb, line 17 def convert_datetime(date_symbol_or_string) attribute = date_symbol_or_string.to_s return nil if self[attribute + '(1i)'].nil? || self[attribute + '(2i)'].nil? || self[attribute + '(3i)'].nil? || self[attribute + '(4i)'].nil? || self[attribute + '(5i)'].nil? return Time.local(self[attribute + '(1i)'].to_i, self[attribute + '(2i)'].to_i, self[attribute + '(3i)'].to_i, self[attribute + '(4i)'].to_i, self[attribute + '(5i)'].to_i) end
rekey(key_map=nil, &block)
click to toggle source
Borrowed from github.com/rubyworks/facets
# File lib/dm_ruby_extensions/extend_hash.rb, line 62 def rekey(key_map=nil, &block) raise ArgumentError, "argument or block" if key_map && block if !(key_map or block) block = lambda{|k| k.to_sym} end if block hash = dup.clear if block.arity.abs == 1 each_pair do |k, v| hash[block[k]] = v #hash[block[k] || k] = v end else each_pair do |k, v| hash[block[k,v]] = v #hash[block[k,v] || k] = v end end else #hash = dup.clear # to keep default_proc #(keys - key_map.keys).each do |key| # hash[key] = self[key] #end #key_map.each do |from, to| # hash[to] = self[from] if key?(from) #end hash = dup # to keep default_proc key_map.each_pair do |from, to| hash[to] = hash.delete(from) if hash.key?(from) end end hash end
rekey!(key_map=nil, &block)
click to toggle source
Synonym for Hash#rekey
, but modifies the receiver in place (and returns it).
foo = { :name=>'Gavin', :wife=>:Lisa } foo.rekey!{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa } foo #=> { "name"=>"Gavin", "wife"=>:Lisa }
CREDIT: Trans, Gavin Kistner
# File lib/dm_ruby_extensions/extend_hash.rb, line 105 def rekey!(key_map=nil, &block) replace(rekey(key_map, &block)) end
url_query_string(leading_slash = true)
click to toggle source
Convert hash of parameters to a query string
# File lib/dm_ruby_extensions/extend_hash.rb, line 25 def url_query_string(leading_slash = true) (leading_slash ? "/?" : "?") << URI.escape(self.collect{|k,v| "#{k}=#{v}"}.join('&')) end