Last active
March 27, 2020 04:53
-
-
Save firedev/4618462 to your computer and use it in GitHub Desktop.
Easy localization for Rails model attributes. Models should have attributes ending with `_<locale>`, i.e. `title_en`, `title_ru`. `attr_translated :title` will add a `.title` method. If `.title_<current_locale>` is empty, `.title_en` will be returned.
This file contains 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
# localized.rb | |
# | |
# Usage: | |
# | |
# include Localized | |
# attr_translated :title | |
# | |
# Model.title now returns title_<locale> or falls back to title_en | |
# | |
module Localized | |
def self.included(base) | |
def base.attr_translated attr | |
define_method attr do | |
if (local=send "#{attr}_#{I18n.locale}").blank? | |
send "#{attr}_en" | |
else | |
local | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment