Class: Traductor::InterpolationGuard
- Inherits:
-
Object
- Object
- Traductor::InterpolationGuard
- Defined in:
- lib/traductor/interpolation_guard.rb
Constant Summary collapse
- PATTERNS =
[ /(%\{[^}]+\})/, # Ruby/Rails: %{name} /(\{\{[^}]+\}\})/, # Handlebars/React: {{variable}} /(\$\{[^}]+\})/, # ES6 template literals: ${variable} ].freeze
- COMBINED_PATTERN =
Regexp.union(PATTERNS)
Instance Method Summary collapse
-
#initialize ⇒ InterpolationGuard
constructor
A new instance of InterpolationGuard.
-
#protect(text) ⇒ Object
Replace interpolation variables with numbered placeholders.
- #reset! ⇒ Object
-
#restore(text) ⇒ Object
Restore original interpolation variables from placeholders.
Constructor Details
#initialize ⇒ InterpolationGuard
Returns a new instance of InterpolationGuard.
13 14 15 16 |
# File 'lib/traductor/interpolation_guard.rb', line 13 def initialize @placeholders = {} @counter = 0 end |
Instance Method Details
#protect(text) ⇒ Object
Replace interpolation variables with numbered placeholders
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/traductor/interpolation_guard.rb', line 19 def protect(text) return text unless text.is_a?(String) text.gsub(COMBINED_PATTERN) do |match| placeholder = "__TVAR#{@counter}__" @placeholders[placeholder] = match @counter += 1 placeholder end end |
#reset! ⇒ Object
41 42 43 44 |
# File 'lib/traductor/interpolation_guard.rb', line 41 def reset! @placeholders.clear @counter = 0 end |
#restore(text) ⇒ Object
Restore original interpolation variables from placeholders
31 32 33 34 35 36 37 38 39 |
# File 'lib/traductor/interpolation_guard.rb', line 31 def restore(text) return text unless text.is_a?(String) result = text.dup @placeholders.each do |placeholder, original| result.gsub!(placeholder, original) end result end |