DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

SQL-Injection Save Parser Generates ORDER BY Statement

02.22.2007
| 2768 views |
  • submit to reddit
        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'

module ActiveRecord
  class Base
    class << self

      def parse_order( order )
        order = order.to_s.gsub /([ \+\-][a-z_]+)/ do |match|
          next unless self.column_names.include?( match[1..-1] )

          case match[0, 1]
          when '-' then "#{ match[1..-1] } DESC, "
          else "#{ match[1..-1] }, "
          end
        end and order[0..-3]
      end
    
    end
  end
end