mirror of
https://github.com/Shopify/liquid.git
synced 2026-09-16 17:30:43 -07:00
Add sketch of I18n error translation
This commit is contained in:
@@ -48,6 +48,7 @@ end
|
||||
require "liquid/version"
|
||||
require 'liquid/lexer'
|
||||
require 'liquid/parser'
|
||||
require 'liquid/i18n'
|
||||
require 'liquid/drop'
|
||||
require 'liquid/extensions'
|
||||
require 'liquid/errors'
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
require 'yaml'
|
||||
require 'delegate'
|
||||
|
||||
module Liquid
|
||||
class I18n
|
||||
class TranslationError < StandardError
|
||||
end
|
||||
|
||||
def initialize(path)
|
||||
@path = path
|
||||
end
|
||||
|
||||
def translate(name, vars = {})
|
||||
interpolate(deep_fetch_translation(name), vars)
|
||||
end
|
||||
alias_method :t, :translate
|
||||
|
||||
class << self
|
||||
def translate(name, vars = {})
|
||||
@@global.translate(name, vars)
|
||||
end
|
||||
alias_method :t, :translate
|
||||
|
||||
def global=(translator)
|
||||
@@global = translator
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def interpolate(name, vars)
|
||||
name.gsub(/:(\w+)/) do
|
||||
vars[$1.to_sym] or raise TranslationError, translate("errors.i18n.undefined_interpolation", :key => $1, :name => name)
|
||||
end
|
||||
end
|
||||
|
||||
def deep_fetch_translation(name)
|
||||
name.split('.').reduce(locale) do |level, cur|
|
||||
level[cur] or raise TranslationError, translate("errors.i18n.unknown_translation", :name => name)
|
||||
end
|
||||
end
|
||||
|
||||
def locale
|
||||
@locale ||= YAML.load_file(@path)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
errors:
|
||||
i18n:
|
||||
unknown_translation: "Translation for :name does not exist in locale"
|
||||
undefined_interpolation: "Undefined key :key for interpolation in translation :name"
|
||||
template:
|
||||
argument_hash_or_context: "Expect Hash or Liquid::Context as parameter"
|
||||
syntax_error:
|
||||
tag_termination: "Tag ':token' was not properly terminated with regexp: :inspection"
|
||||
@@ -119,7 +119,7 @@ module Liquid
|
||||
when nil
|
||||
Context.new(assigns, instance_assigns, registers, @rethrow_errors, @resource_limits)
|
||||
else
|
||||
raise ArgumentError, "Expect Hash or Liquid::Context as parameter"
|
||||
raise ArgumentError, I18n.translate("errors.template.argument_hash_or_context")
|
||||
end
|
||||
|
||||
case args.last
|
||||
|
||||
Reference in New Issue
Block a user