Skip to content

Instantly share code, notes, and snippets.

@firedev
Last active March 27, 2020 04:53
Show Gist options
  • Save firedev/4618462 to your computer and use it in GitHub Desktop.
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.
# 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