Class: Hash
Instance Method Summary collapse
-
#-(*args) ⇒ Object
lets you do : :fish=>‘trout’, :rodent=>‘vole’ - [:simian, :fish] => :rodent=>‘vole’.
-
#get_binding ⇒ Object
The way bindings work in ruby 1.9+ has changed so add this to work for both 1.8 and 1.9.
- #recursive_stringify_keys ⇒ Object
- #recursive_symbolize_keys! ⇒ Object
- #symbolize_keys! ⇒ Object
-
#to_conditions(allowed_keys, column_aliases = {}) ⇒ Object
Allows you to convert a hash to an array suitable for use in an ActiveRecord finder conditions clause.
Instance Method Details
#-(*args) ⇒ Object
lets you do :
{:simian=>'chimp', :fish=>'trout', :rodent=>'vole'} - [:simian, :fish]
> :rodent=>‘vole’
57 58 59 60 61 62 |
# File 'lib/itrigga/core_ext/hash.rb', line 57 def -( *args ) keys = *args.to_a.flatten hash = self.clone keys.each{ |k| hash.delete(k) } hash end |
#get_binding ⇒ Object
The way bindings work in ruby 1.9+ has changed so add this to work for both 1.8 and 1.9
68 69 70 |
# File 'lib/itrigga/core_ext/hash.rb', line 68 def get_binding return binding end |
#recursive_stringify_keys ⇒ Object
21 22 23 24 25 26 |
# File 'lib/itrigga/core_ext/hash.rb', line 21 def recursive_stringify_keys inject({}) do |, (key, value)| [key.to_s] = value.kind_of?(Hash) ? value.recursive_stringify_keys : value end end |
#recursive_symbolize_keys! ⇒ Object
11 12 13 14 15 16 17 18 19 |
# File 'lib/itrigga/core_ext/hash.rb', line 11 def recursive_symbolize_keys! inject({}) do |, (key, value)| [(key.to_sym rescue key) || key] = value.is_a?( Hash ) ? value.recursive_symbolize_keys! : value end end |
#symbolize_keys! ⇒ Object
4 5 6 7 8 9 |
# File 'lib/itrigga/core_ext/hash.rb', line 4 def symbolize_keys! inject({}) do |, (key, value)| [(key.to_sym rescue key) || key] = value end end |
#to_conditions(allowed_keys, column_aliases = {}) ⇒ Object
Allows you to convert a hash to an array suitable for use in an ActiveRecord finder conditions clause
e.g.
{:fish=>'trout', :cheese=>'gruyere', :rodent=>'vole'}.to_conditions( [:fish, :cheese], {:cheese=>:fromage})
=> ["(fish = ?) AND (fromage = ?)", 'trout', 'gruyere']
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/itrigga/core_ext/hash.rb', line 36 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 |