Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Florian Aßmann

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Find every path and it's value in a Hash

Extends Hash class with each_path method.

This method takes a block as argument which is called each time a the recursivly searched Hash returns a key that does not point to another Hash.

Example:
   1  
   2  paths = []
   3  complex_hash = Hash[
   4    :a => { :aa => '1', :ab => '2' },
   5    :b => { :ba => '3', :bb => '4' }
   6  ]
   7  complex_hash.each_path { |path, value| paths << [ path, value ] }
   8  paths.inspect
   9  # => "[[\"b/ba/\", \"3\"], [\"b/bb/\", \"4\"], [\"a/aa/\", \"1\"], [\"a/ab/\", \"2\"]]"


   1  
   2  class Hash
   3    def each_path
   4      raise ArgumentError unless block_given?
   5      self.class.each_path( self ) { |path, object| yield path, object }
   6    end
   7  
   8    protected
   9    def self.each_path( object, path = '', &block )
  10      if object.is_a?( Hash ) then object.each do |key, value|
  11          self.each_path value, "#{ path }#{ key }/", &block
  12        end
  13      else yield path, object
  14      end
  15    end
  16  end

SQL-Injection save parser generates ORDER BY statement

Parses a string and generates an SQL order statement.

Because it's SQL-Injection save you can put it in your link_to method as :order => '+name' and then call #parse_order( params[:order] ).

Examples:
'+name' => 'name'
'+lastname+firstname' => 'lastname, firstname'
'+lastname-gender' => 'lastname, gender DESC'

   1  
   2  module ActiveRecord
   3    class Base
   4      class << self
   5  
   6        def parse_order( order )
   7          order = order.to_s.gsub /([ \+\-][a-z_]+)/ do |match|
   8            next unless self.column_names.include?( match[1..-1] )
   9  
  10            case match[0, 1]
  11            when '-' then "#{ match[1..-1] } DESC, "
  12            else "#{ match[1..-1] }, "
  13            end
  14          end and order[0..-3]
  15        end
  16      
  17      end
  18    end
  19  end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS