Created
November 5, 2010 19:30
-
-
Save nertzy/664645 to your computer and use it in GitHub Desktop.
Quick way to build a case statement in SQL using ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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