Sha256: 838fc6bc9303bc58956c2089746c76af7bfa6c6b6fb5fab825600b9a77a8dffa

Contents?: true

Size: 950 Bytes

Versions: 12

Compression:

Stored size: 950 Bytes

Contents

require 'yaml'

module Liquid
  class I18n
    DEFAULT_LOCALE = File.join(File.expand_path(File.dirname(__FILE__)), "locales", "en.yml")

    class TranslationError < StandardError
    end

    attr_reader :path

    def initialize(path = DEFAULT_LOCALE)
      @path = path
    end

    def translate(name, vars = {})
      interpolate(deep_fetch_translation(name), vars)
    end
    alias_method :t, :translate

    def locale
      @locale ||= YAML.load_file(@path)
    end

    private
    def interpolate(name, vars)
      name.gsub(/%\{(\w+)\}/) {
        # raise TranslationError, "Undefined key #{$1} for interpolation in translation #{name}"  unless vars[$1.to_sym]
        "#{vars[$1.to_sym]}"
      }
    end

    def deep_fetch_translation(name)
      name.split('.'.freeze).reduce(locale) do |level, cur|
        level[cur] or raise TranslationError, "Translation for #{name} does not exist in locale #{path}"
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
locomotivecms-liquid-4.0.0 lib/liquid/i18n.rb
liquid-3.0.6 lib/liquid/i18n.rb
liquid-3.0.5 lib/liquid/i18n.rb
liquid-3.0.4 lib/liquid/i18n.rb
liquid-3.0.3 lib/liquid/i18n.rb
liquid-3.0.2 lib/liquid/i18n.rb
locomotivecms-liquid-4.0.0.alpha2 lib/liquid/i18n.rb
locomotivecms-liquid-4.0.0.alpha1 lib/liquid/i18n.rb
locomotivecms-liquid-4.0.0.alpha lib/liquid/i18n.rb
liquid-3.0.1 lib/liquid/i18n.rb
liquid-3.0.0 lib/liquid/i18n.rb
liquid-3.0.0.rc1 lib/liquid/i18n.rb