Created
February 15, 2014 16:19
-
-
Save knu/9021524 to your computer and use it in GitHub Desktop.
Adds per-column charset/collation support to ActiveRecord's MySQL adapter. Based on: http://qiita.com/kamipo/items/4763bcffce2140f030b3
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
require 'active_record' | |
module ActiveRecord::ConnectionAdapters | |
class ColumnDefinition | |
module CharsetSupport | |
attr_accessor :charset, :collation | |
end | |
prepend CharsetSupport | |
end | |
class TableDefinition | |
module CharsetSupport | |
def column(name, type = nil, options = {}) | |
super | |
column = self[name] | |
column.charset = options[:charset] | |
column.collation = options[:collation] | |
self | |
end | |
end | |
prepend CharsetSupport | |
end | |
class AbstractMysqlAdapter | |
module CharsetSupport | |
def prepare_column_options(column, types) | |
spec = super | |
conn = ActiveRecord::Base.connection | |
spec[:charset] = column.charset.inspect if column.charset && column.charset != conn.charset | |
spec[:collation] = column.collation.inspect if column.collation && column.collation != conn.collation | |
spec | |
end | |
def add_column_options!(sql, options) | |
if options[:charset] | |
sql << " CHARACTER SET #{options[:charset]}" | |
end | |
if options[:collation] | |
sql << " COLLATE #{options[:collation]}" | |
end | |
super | |
end | |
def migration_keys | |
super + [:charset, :collation] | |
end | |
end | |
prepend CharsetSupport | |
class SchemaCreation | |
module CharsetSupport | |
def column_options(o) | |
column_options = super | |
column_options[:charset] = o.charset unless o.charset.nil? | |
column_options[:collation] = o.collation unless o.collation.nil? | |
column_options | |
end | |
end | |
prepend CharsetSupport | |
end | |
class Column | |
module CharsetSupport | |
attr_reader :charset | |
def initialize(*args) | |
super | |
@charset = @collation[/\A[^_]+/] unless @collation.nil? | |
end | |
end | |
prepend CharsetSupport | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what version of Active Record was this written for?