Created
March 14, 2012 05:29
-
-
Save pwim/2034297 to your computer and use it in GitHub Desktop.
GlobalizeAccessors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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