Sha256: 08092871274d6eed3605e989877eec02774bddb30514ae62eaea3f5444031c6a

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require "active_support"
require "active_support/core_ext"
require "mighty_tap"
require "yaml"
require_relative "../skala"

module Skala::I18n
  def self.included(klass)
    klass.extend(ClassMethods)
  end

  module ClassMethods
    def load_locales_from_directory(path)
      Dir.glob("#{File.expand_path(path)}/*.yml").inject({}) do |_locales, _filename|
        _locales.mtap(:deep_merge!, YAML.load_file(_filename))
      end
    end

    # override this to provide locales
    def locales
      {}
    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(".")
      
      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

  def translate(*args)
    self.class.translate(*args)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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