require "deep_merger" require "yaml" module Celsius::I18n 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) 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 end end