Sha256: 9b39efc58551bb177ec92a0a4e35f52bcb0f99bcb3d66d7bf73acce3521908ec

Contents?: true

Size: 938 Bytes

Versions: 5

Compression:

Stored size: 938 Bytes

Contents

require 'yaml'

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

    TranslationError = Class.new(StandardError)

    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+)\}/) do
        # raise TranslationError, "Undefined key #{$1} for interpolation in translation #{name}"  unless vars[$1.to_sym]
        (vars[$1.to_sym]).to_s
      end
    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

5 entries across 5 versions & 2 rubygems

Version Path
liquid-4.0.4 lib/liquid/i18n.rb
metanorma-cli-1.3.4 gems/ruby/2.6.0/gems/liquid-4.0.3/lib/liquid/i18n.rb
metanorma-cli-1.3.3.1 gems/ruby/2.6.0/gems/liquid-4.0.3/lib/liquid/i18n.rb
liquid-4.0.3 lib/liquid/i18n.rb
liquid-4.0.2 lib/liquid/i18n.rb