Skip to content

Instantly share code, notes, and snippets.

@pwim
Created March 14, 2012 05:29
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 pwim/2034297 to your computer and use it in GitHub Desktop.
Save pwim/2034297 to your computer and use it in GitHub Desktop.
GlobalizeAccessors
# allows directly accessing the locale specific fields such as text_en and text_ja without using fallbacks
module GlobalizeAccessors
def translates(*attr_names)
super
attr_names.each do |attr_name|
I18n::AVAILABLE_LOCALES.map(&:to_sym).each do |locale|
# writer
define_method :"#{attr_name}_#{locale}=" do |value|
write_attribute(attr_name, value, :locale => locale)
end
# reader
define_method :"#{attr_name}_#{locale}" do
val = globalize.stash.contains?(locale, attr_name) ? globalize.send(:fetch_stash, locale, attr_name) : globalize.send(:fetch_attribute, locale, attr_name)
if self.class.respond_to?(:sanitizable_attributes) && self.class.sanitizable_attributes.include?(attr_name.to_sym) && val
val = val.html_safe
end
val
end
# protection
if accessible_attributes.include?(attr_name)
attr_accessible :"#{attr_name}_#{locale}"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment