Sha256: e19f347c2f8664751150d91b27d7ad01e7b4eee267c67b3354ac04e63394baa5

Contents?: true

Size: 1.03 KB

Versions: 4

Compression:

Stored size: 1.03 KB

Contents

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
celsius-0.4.3 lib/celsius/i18n.rb
celsius-0.4.2 lib/celsius/i18n.rb
celsius-0.4.1 lib/celsius/i18n.rb
celsius-0.4.0 lib/celsius/i18n.rb