Sha256: 242619e08557267569b6c2d7f6103c058d2f65b797cab151ee434f1432c3bcbe

Contents?: true

Size: 1.45 KB

Versions: 2

Compression:

Stored size: 1.45 KB

Contents

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
  
  
  # 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
  
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
itrigga-core_ext-0.3.0 lib/itrigga/core_ext/hash.rb
itrigga-core_ext-0.2.2 lib/itrigga/core_ext/hash.rb