Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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