Skip to content

Instantly share code, notes, and snippets.

@kbrock
Created June 16, 2010 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kbrock/440903 to your computer and use it in GitHub Desktop.
Save kbrock/440903 to your computer and use it in GitHub Desktop.
module ActiveRecord
##idea is from lovdbyless
##These extensions give database specific implementations for common functions
module ConnectionAdaptersExt
module MySQL
def rand
'RANDOM()'
end
def now
'NOW()'
end
def birthyear(fld)
"YEAR(#{fld})"
end
def age(fld)
#"DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(#{fld})), '%Y')+0"
#"DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(#{fld}, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(#{fld}, '00-%m-%d'))"
"YEAR(CURDATE()) - YEAR(#{fld}) - IF(RIGHT(CURDATE(),5) < RIGHT(#{fld},5),1,0)"
end
def least(fld,value,cast=true)
"least(#{fld},#{value})"
end
def boolean_value(val)
val
end
end
module Posgres
def rand
'RAND()'
end
def now
"NOW()"
end
def birthyear(fld)
"date_part('year',#{fld})"
end
#age(a) will say the age from today - exactly what we want
def age(fld)
"date_part('year', age(#{fld}))"
end
def least(fld,value,cast=true)
if cast
"least(cast(#{fld} as INTEGER),#{value})"
else
"least(#{fld},#{value})"
end
end
def boolean_value(val)
val
end
end
module SQLite
def rand
'RAND()'
end
def age(fld)
"(#{now}-#{fld})"
end
def birthyear(fld)
"cast(#{fld} as integer)"
end
def now
"datetime('now')"
end
def least(fld,value,cast=true)
"min(#{fld},#{value})"
end
def boolean_value(val)
val ? 't' : 'f'
end
def import_csv(file,table)
".import #{file} #{table}"
end
end
end
end
case ActiveRecord::Base.connection.adapter_name
when 'MySQL'
ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:include, ActiveRecord::ConnectionAdaptersExt::MySQL)
when /SQLite/
ActiveRecord::ConnectionAdapters::AbstractAdapter.send(:include, ActiveRecord::ConnectionAdaptersExt::SQLite)
else # 'PostgreSQL' ...
ActiveRecord::ConnectionAdapters::AbstractAdapter.send(:include, ActiveRecord::ConnectionAdaptersExt::Posgres)
end
Account.scoped(:conditions => ['active = ?',ActiveRecord::Base.connection.boolean_value(true)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment