Skip to content

Instantly share code, notes, and snippets.

@haifeng
Created August 20, 2012 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save haifeng/3406099 to your computer and use it in GitHub Desktop.
Save haifeng/3406099 to your computer and use it in GitHub Desktop.
i18n positions
$LOAD_PATH << './lib'
require 'i18n.rb'
class Backend < I18n::Backend::Simple
include I18n::Backend::Metadata
end
# if string.respond_to?(:translation_metadata)
# string.translation_metadata[:positions] ||= {}
# string.translation_metadata[:positions][value] = [$~.begin(1), $~.begin(1) + value.length]
# end
I18n.backend = Backend.new
I18n.backend.store_translations(:en, :foo => "Hi %{name}, welcome to %{position}, im %{name}")
# I18n.backend.store_translations(:en, :foo => "Hi %{name}, welcome to %{position}")
translation = I18n.t(:foo, :name => 'David', :position => 'Toronto')
p translation
p translation.translation_metadata
p translation.translation_metadata[:values]
# heavily based on Masao Mutoh's gettext String interpolation extension
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
module I18n
INTERPOLATION_PATTERN = Regexp.union(
/%%/,
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
)
class << self
def interpolate(string, values)
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
interpolate_hash(string, values)
end
def interpolate_hash(string, values)
# def string.position_foo
# @positions ||= {}
# end
positions = {}
offset = 0
string.gsub(INTERPOLATION_PATTERN) do |match|
if match == '%%'
'%'
else
key = ($1 || $2).to_sym
value = values.key?(key) ? values[key] : raise(MissingInterpolationArgument.new(values, string))
value = value.call(values) if value.respond_to?(:call)
# puts "value: #{value} (start: #{$~.begin(1)}, end:#{$~.begin(1) + value.length})"
positions[key] = [offset + $~.begin(1) - 2, offset + $~.begin(1) - 2 + value.length - 1]
# %{name} %{position}
# David Toronto
offset + value.length - (key.size + 3)
$3 ? sprintf("%#{$3}", value) : value
end
end.tap{|result|
result.translation_metadata[:positions] = positions if result.respond_to?(:translation_metadata)
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment