Skip to content

Instantly share code, notes, and snippets.

@sshaw
Created March 15, 2014 16:19
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 sshaw/9569849 to your computer and use it in GitHub Desktop.
Save sshaw/9569849 to your computer and use it in GitHub Desktop.
PostgreSQL casting in Rails using the x::typename construct and ActiveRecord's where method
# Experiment, only tested under Rails 3.2.16, not sure how useful it really is...
# "Works" only with where conditions using a Hash
#
# Example:
# User.where :created_at::date => "2014-01-01" # :created_at is a timestamp
#
module PgCast
# All of these are not really viable
TYPES = %w[any char abstime aclitem anyarray anyelement anyenum anynonarray bigint bit bit varying boolean box bytea character character varying cid cidr circle cstring date double precision gtsvector inet int2vector integer internal interval language_handler line lseg macaddr money name numeric oid oidvector opaque path point polygon real record refcursor regclass regconfig regdictionary regoper regoperator regproc regprocedure regtype reltime smallint smgr text tid time with time zone time without time zone timestamp with time zone timestamp without time zone tinterval trigger tsquery tsvector txid_snapshot unknown uuid void xid xml]
class TypeCast < Struct.new(:column, :type)
def to_s
self
end
def to_sym
self
end
end
module Symbol
TYPES.each do |type|
type.strip!
define_method(type) do
TypeCast.new(self, type)
end
end
end
end
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
def quote_column_name(name)
!name.is_a?(PgCast::TypeCast) ?
PGconn.quote_ident(name.to_s) :
PGconn.quote_ident(name.column.to_s) << "::#{name.type}"
end
end
Symbol.send(:include, PgCast::Symbol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment