Friday, August 22, 2008

Extending Globalize

Came across an interesting situation where i had a simple edit form where the translator is supposed to enter the description of the selected product and the data will be stored as the current language translation for which the Locale is set. The application uses globalize for localization. The problem was that i had to access the native description of the product(in english) as well and display it on the same page to make it easy for the translator. I came up with a very generic solution a module that can be included in any model and will give you a method get_native_attribute_name that will give you the value of the specified attribute in the base language of your app(in this case english)
Here is the code

module NativeAttributes

def self.included(base)
base.class_eval do
alias_method :method_missing_without_native_attrs, :method_missing
include NativeAttributes::InstanceMethods
end
end

module InstanceMethods
def get_native_attribute(attrib)
table = self.class.table_name
self.class.find_by_sql("select #{attrib} from #{table} where id = #{self.id}").first.send(attrib)
end

def method_missing(meth, *args,&block)
if meth.to_s.include?('get_native_')
current_locale = "#{Locale.active.language.code}-#{Locale.active.country.code}"
Locale.set('en-US')
self.reload
native_attribute = self.get_native_attribute(meth.to_s.gsub('get_native_',''))
Locale.set current_locale
self.reload
return native_attribute
else
method_missing_without_native_attrs(meth,*args,&block)
end
end
end
end

No comments: