require "yaml" require_relative "../skala" module Skala::I18n require_relative "./i18n/deep_merger" def self.included(klass) unless klass.class_variable_defined?(:@@locales) klass.class_variable_set(:@@locales, {}) end klass.extend(ClassMethods) end module ClassMethods def load_locales_from_directory(path) # class_variable_get is needed to avoid implicite referencing the module instead of the including class Dir.glob("#{File.expand_path(path)}/*.yml").inject(self.class_variable_get(:@@locales)) do |locales, filename| DeepMerger.deep_merge!(locales, YAML.load_file(filename)) end end end def translate(key, options = {}) raise "Destination locale missing!" if options[:locale].nil? fully_qualified_key = "#{options[:locale]}.#{key}" keys_path = fully_qualified_key.split(".") locales = self.class.class_variable_get(:@@locales) translated_key = keys_path.inject(locales) do |hash, hash_key| unless hash.nil? hash[hash_key.to_s] || hash[hash_key.to_sym] end end || keys_path.last translated_key.gsub(/%{[^}]+}+/) do |match| interpolation_key = match.gsub(/(\A%{)|(}\Z)/, "") options[interpolation_key.to_s] || options[interpolation_key.to_sym] || match end end end