Skip to content

Instantly share code, notes, and snippets.

@knu
Created February 15, 2014 16:19
Show Gist options
  • Save knu/9021524 to your computer and use it in GitHub Desktop.
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
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
@LukasBeaton
Copy link

what version of Active Record was this written for?

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