29b28146ffb211cc6d2076b6525b256e25d98843
[packages/precise/mcollective.git] / lib / mcollective / vendor / i18n / lib / i18n / interpolate / ruby.rb
1 # heavily based on Masao Mutoh's gettext String interpolation extension
2 # http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
3
4 module I18n
5   INTERPOLATION_PATTERN = Regexp.union(
6     /%%/,
7     /%\{(\w+)\}/,                               # matches placeholders like "%{foo}"
8     /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/  # matches placeholders like "%<foo>.d"
9   )
10
11   class << self
12     def interpolate(string, values)
13       raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
14       raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
15       interpolate_hash(string, values)
16     end
17
18     def interpolate_hash(string, values)
19       string.gsub(INTERPOLATION_PATTERN) do |match|
20         if match == '%%'
21           '%'
22         else
23           key = ($1 || $2).to_sym
24           value = values.key?(key) ? values[key] : raise(MissingInterpolationArgument.new(values, string))
25           value = value.call(values) if value.respond_to?(:call)
26           $3 ? sprintf("%#{$3}", value) : value
27         end
28       end
29     end
30   end
31 end