Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Attempt w/initializer to monkey-patch active record in rails 3
require 'set'
require 'active_record/connection_adapters/mysql_adapter'
#
# Monkey-patch ActiveRecord (and the MySQL connection adapter specifically) to
# make the default true value: -1
#
# Also change the MySQL connection adapter so that migrations with a :timestamp
# column type will create a MySQL TIMESTAMP field instead of a DATETIME field.
#
# The purpose here is to have our database definitions match the behaviour and
# and requirements of a MySQL database that is backing a Microsoft Access 2003
# application, namely:
# - Each table MUST have a TIMESTAMP (not DATETIME) column
# - All booleans are stored in TINYINT(1) columns with TRUE being: -1
#
module ActiveRecord
module ConnectionAdapters
class Column
#
# Recognize -1 (and '-1') values on boolean columns as true. The existing
# set of recognized values for "true" is defined in the TRUE_VALUES
# constant which is only read/accessed via the #value_to_boolean method.
#
TRUE_VALUES_WITH_NEGATIVE_ONES = [-1, '-1'].to_set
class << self
def value_to_boolean_with_negative_ones(value)
return true if TRUE_VALUES_WITH_NEGATIVE_ONES.include?(value)
value_to_boolean_without_negative_ones(value)
end
alias_method_chain :value_to_boolean, :negative_ones
end
end
class MysqlAdapter
#
# Set string '-1' as the default "true" value for boolean columns using
# the MySQL Adapter. The original true value is defined in the QUOTED_TRUE
# constant which is only read/accessed via the #quoted_true method.
#
QUOTED_TRUE_AS_NEGATIVE_ONE = '-1'.freeze
def quoted_true_as_negative_one
QUOTED_TRUE_AS_NEGATIVE_ONE
end
alias_method :quoted_true, :quoted_true_as_negative_one
#
# Make the MySQL Adapter create columns defined as a :timestamp column in
# migrations as the MySQL "TIMESTAMP" data type instead of DATETIME. The
# existing set of column type definitions is defined in the
# NATIVE_DATABASE_TYPES constant (a hash) which is only read/accessed via
# the #native_database_types method.
#
NATIVE_DATABASE_TYPES_WITH_TIMESTAMP = {
:timestamp => { :name => "timestamp" }
}
def native_database_types_with_timestamp
@native_database_types_with_timestamp ||=
native_database_types_without_timestamp.merge(
NATIVE_DATABASE_TYPES_WITH_TIMESTAMP
)
end
alias_method_chain :native_database_types, :timestamp
end
end
end
@wreimers
Copy link

wreimers commented Dec 14, 2011

I found that in Rails 3.1, I had to get AR to initialize properly. 'require' didnt work for me.

https://gist.github.com/1478997

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment