Created
July 1, 2014 23:22
-
-
Save xymbol/dec31bbfaeac5e1d0e64 to your computer and use it in GitHub Desktop.
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
# This class provides most of the features you'd get from i18n-active_record, | |
# only simpler and lighter. | |
class Translation < ActiveRecord::Base | |
class Backend < I18n::Backend::KeyValue | |
module Implementation | |
attr_reader :store | |
def initialize(subtress = true) | |
@store = Store.new | |
super store, subtress | |
end | |
def available_locales | |
store.locales.map &:to_sym | |
end | |
end | |
include I18n::Backend::Memoize, Implementation | |
end | |
class Store | |
def [](key) | |
scope.find_by!(key: key).value | |
rescue ActiveRecord::RecordNotFound | |
nil | |
end | |
# FIXME: you might want to support key deletion by setting to a nil value. | |
def []=(key, value) | |
record = scope.find_or_initialize_by(key: key) | |
record.update! value: value | |
rescue ActiveRecord::RecordInvalid | |
nil | |
end | |
def keys | |
scope.pluck(:key) | |
end | |
# Returns a list of locales as strings using the de-normalized locale | |
# column. Added to make available_locales faster. | |
def locales | |
scope.select(:locale).distinct.pluck(:locale) | |
end | |
private | |
def scope | |
Translation | |
end | |
end | |
validates :locale, :key, presence: true | |
validates :key, uniqueness: true | |
before_validation :set_locale | |
private | |
# Sets a locale attribute from the key. | |
def set_locale | |
self.locale = locale_from key | |
end | |
def locale_from(key) | |
$` if key =~ /\./ | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment