Skip to content

Instantly share code, notes, and snippets.

@mrkn
Created April 28, 2010 07:30
Show Gist options
  • Save mrkn/381834 to your computer and use it in GitHub Desktop.
Save mrkn/381834 to your computer and use it in GitHub Desktop.
if defined?(ActiveRecord)
class ActiveRecord::Base
def read_attribute_with_enforcing_utf8(attr_name)
v = read_attribute_without_enforcing_utf8(attr_name)
if String === v && column_for_attribute(attr_name).text?
return v.force_encoding(Encoding::UTF_8) if v.encoding == Encoding::ASCII_8BIT
end
return v
end
alias_method_chain :read_attribute, :enforcing_utf8
class << self
private
def define_read_method_with_enforcing_utf8(symbol, attr_name, column)
define_read_method_without_enforcing_utf8(symbol, attr_name, column)
if column.text?
self.class_eval <<-END_DEFINITION, __FILE__, __LINE__
def #{symbol}_with_enforcing_utf8
v = #{symbol}_without_enforcing_utf8
v = v.force_encoding(Encoding::UTF_8) if v && v.encoding == Encoding::ASCII_8BIT
return v
end
alias_method_chain :#{symbol}, :enforcing_utf8
END_DEFINITION
end
end
alias_method_chain :define_read_method, :enforcing_utf8
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment