From affcda0b92f614b6b0a1cb55a55e7be75b77f81c Mon Sep 17 00:00:00 2001 From: Seb Bacon Date: Thu, 13 Jan 2011 17:42:44 +0000 Subject: override gettext "_" behaviour to also support interpolation --- lib/i18n_fixes.rb | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 lib/i18n_fixes.rb (limited to 'lib/i18n_fixes.rb') diff --git a/lib/i18n_fixes.rb b/lib/i18n_fixes.rb new file mode 100644 index 000000000..9d7a999dd --- /dev/null +++ b/lib/i18n_fixes.rb @@ -0,0 +1,37 @@ +# override behaviour in fast_gettext/translation.rb +# so that we can interpolate our translation strings nicely + +def _(key, options = {}) + translation = FastGettext._(key) || key + gettext_interpolate(translation, options) +end + +INTERPOLATION_RESERVED_KEYS = %w(scope default) +MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ + +def gettext_interpolate(string, values) + return string unless string.is_a?(String) + if values.is_a?(Hash) + string.gsub(MATCH) do + escaped, pattern, key = $1, $2, $2.to_sym + + if escaped + pattern + elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) + raise ReservedInterpolationKey.new(pattern, string) + elsif !values.include?(key) + raise MissingInterpolationArgument.new(pattern, string) + else + values[key].to_s + end + end + else + reserved_keys = if defined?(I18n::RESERVED_KEYS) # rails 3+ + I18n::RESERVED_KEYS + else + I18n::Backend::Base::RESERVED_KEYS + end + + string % values.except(*reserved_keys) + end +end -- cgit v1.2.3