Skip to content

Instantly share code, notes, and snippets.

@cthiel
Created June 15, 2009 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cthiel/130145 to your computer and use it in GitHub Desktop.
Save cthiel/130145 to your computer and use it in GitHub Desktop.
recode_legacy_database.rb
# 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