Created
June 15, 2009 14:49
-
-
Save cthiel/130145 to your computer and use it in GitHub Desktop.
recode_legacy_database.rb
This file contains hidden or 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
| # RecodeLegacyDatabase | |
| module Recode #:nodoc: | |
| module Legacy #:nodoc: | |
| module Database #:nodoc: | |
| def self.included(base) #:nodoc: | |
| base.extend ClassMethods | |
| end | |
| module ClassMethods | |
| # recode_legacy_database :from => "ISO-8859-1", :to => "UTF-8" | |
| def recode_legacy_database(*args) | |
| options = { :from => "ISO-8859-1", :to => "UTF-8", :exclude => [] } | |
| options.merge!( args.last.is_a?( Hash ) ? args.last : {} ) | |
| class_inheritable_accessor :options | |
| self.options = options | |
| self.send(:include, Recode::Legacy::Database::InstanceMethods) | |
| end | |
| end | |
| # This module contains instance methods | |
| module InstanceMethods | |
| require 'iconv' | |
| def recode(from, to) | |
| attributes.each do |k,v| | |
| if v.class.to_s == "String" and !v.empty? and !self.options[:exclude].include? k | |
| self[k] = Iconv.conv(to, from, v) rescue v | |
| end | |
| end | |
| end | |
| def after_find | |
| recode(self.options[:from], self.options[:to]) | |
| super | |
| end | |
| def after_initialize | |
| recode(self.options[:from], self.options[:to]) | |
| super | |
| end | |
| def before_save | |
| recode(self.options[:to], self.options[:from]) | |
| end | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment