# -*- encoding : utf-8 -*- class Hash def symbolize_keys! inject({}) do |options, (key, value)| options[(key.to_sym rescue key) || key] = value options end end def recursive_symbolize_keys! inject({}) do |options, (key, value)| options[(key.to_sym rescue key) || key] = value.is_a?( Hash ) ? value.recursive_symbolize_keys! : value options end end def recursive_stringify_keys inject({}) do |options, (key, value)| options[key.to_s] = value.kind_of?(Hash) ? value.recursive_stringify_keys : value options end end # Allows you to convert a hash to an array suitable for use in an ActiveRecord finder conditions clause # # @allowed_keys optional an array of param names to include - if given, any keys NOT in this array will be excluded # @column_aliases optional a hash of param name => column name mappings, for the case where the param name needs mapping to an alternative column name # e.g. # {:fish=>'trout', :cheese=>'gruyere', :rodent=>'vole'}.to_conditions( [:fish, :cheese], {:cheese=>:fromage}) # => ["(fish = ?) AND (fromage = ?)", 'trout', 'gruyere'] def to_conditions( allowed_keys, column_aliases={} ) conds = [ [] ] allowed_keys ||= keys allowed_keys.to_a.each do |k| this_key = ( keys.include?(k.to_sym) ? k.to_sym : (keys.include?(k.to_s) ? k.to_s : nil)) next unless this_key next if self[this_key].blank? conds[0] << "#{column_aliases[this_key.to_sym] ? column_aliases[this_key.to_sym] : this_key.to_s} = ?" conds << self[this_key] end conds[0] = conds[0].map{ |c| "(#{c})" }.join( " AND " ) conds end # lets you do : # {:simian=>'chimp', :fish=>'trout', :rodent=>'vole'} - [:simian, :fish] # => {:rodent=>'vole'} def -( *args ) keys = *args.to_a.flatten hash = self.clone keys.each{ |k| hash.delete(k) } hash end # # The way bindings work in ruby 1.9+ has changed so add this to work for both # 1.8 and 1.9 # def get_binding return binding end end