Skip to content

Instantly share code, notes, and snippets.

@silentshade
Created August 14, 2013 11:59
Show Gist options
  • Save silentshade/6230417 to your computer and use it in GitHub Desktop.
Save silentshade/6230417 to your computer and use it in GitHub Desktop.
require 'i18n'
require 'arel'
module ModelTranslate
def self.included(base)
base.send :extend, Base
end
module Base
def translations *methods
methods.each do |method|
I18n.available_locales.each do |locale|
if ActiveRecord::Base.connection.column_exists? self.arel_table.name.to_sym, "#{method}_#{locale}".to_sym
class_eval <<-EOS, __FILE__, __LINE__
def #{method}
begin
res = send "#{method}_\#\{I18n.locale\}".to_sym
res.size > 0 ? res : send("#{method}_\#\{I18n.default_locale\}".to_sym)
rescue
send "#{method}_\#\{I18n.default_locale\}".to_sym
end
end
def #{method}= *args
begin
res = send "#{method}_\#\{I18n.locale\}=".to_sym, *args
res.size > 0 ? res : send("#{method}_\#\{I18n.default_locale\}=".to_sym, *args)
rescue
send "#{method}_\#\{I18n.default_locale\}=".to_sym, *args
end
end
EOS
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment