diff options
author | Seb Bacon <seb.bacon@gmail.com> | 2011-01-13 17:42:44 +0000 |
---|---|---|
committer | Seb Bacon <seb.bacon@gmail.com> | 2011-03-10 10:00:26 +0000 |
commit | affcda0b92f614b6b0a1cb55a55e7be75b77f81c (patch) | |
tree | 2416b1e5eb50e28d7284b46999ee347aceccea92 /lib | |
parent | acd7b81f4cfaf2db204f1aee1e2e2d21d549db88 (diff) |
override gettext "_" behaviour to also support interpolation
Diffstat (limited to 'lib')
-rw-r--r-- | lib/i18n_fixes.rb | 37 |
1 files changed, 37 insertions, 0 deletions
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 |