Created
September 7, 2014 11:11
-
-
Save aalavandhan/6a90349dddd2e8e44b11 to your computer and use it in GitHub Desktop.
A simple rails utility which cahces data from config/locales/*.yml files as a hash and returns a hash for each specified language file. It also parses and reloads the YAML files everytime they are changed.
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
module Util | |
class MessageHandler | |
@@data = {} | |
class << self | |
def data_in(language) | |
load! if !@@data[language] or (files_changed? and Rails.env.development?) | |
@@data[language][language.to_s] | |
end | |
private | |
def load! | |
parse_file = -> (language, file_path) { | |
@@data[language] ||= YAML.load(File.read(file_path)) | |
} | |
possible_languages.map do |language| | |
parse_file.call( language, locale_file_path(language)) | |
end | |
end | |
def files_changed? | |
@@file_update_checker ||= ActiveSupport::FileUpdateChecker.new(language_file_paths) | |
@@file_update_checker.updated? | |
end | |
def possible_languages | |
[ :en, :es, :pt] | |
end | |
def language_file_paths | |
possible_languages.map{ |l| locale_file_path(l) } | |
end | |
def locale_file_path(language) | |
File.join(Rails.root, locale_relative_file_path(language)) | |
end | |
def locale_relative_file_path(language) | |
File.join('config', 'locales', "#{language.to_s}.yml") | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment