Sha256: 2e48ff3555f59b27f9ccf5d8f53d3215b16bf28300cf93634df1bc1090fa1d0b

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
skala-0.2.0 lib/skala/i18n.rb