Skip to content

Instantly share code, notes, and snippets.

@nertzy
Created November 5, 2010 19:30
Show Gist options
  • Save nertzy/664645 to your computer and use it in GitHub Desktop.
Save nertzy/664645 to your computer and use it in GitHub Desktop.
Quick way to build a case statement in SQL using ActiveRecord
module CaseStatementBuilder
class << self
delegate :connection, :to => ActiveRecord::Base
def build(lhs, values_hash, default_value)
when_expressions = values_hash.sort.map do |rhs, value|
"WHEN #{lhs} = #{connection.quote(rhs)} THEN #{connection.quote(value)}"
end.join(" ")
"CASE #{when_expressions} ELSE #{connection.quote(default_value)} END"
end
private
def connection
ActiveRecord::Base.connection
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment