Created
February 25, 2010 12:28
-
-
Save henrik/314504 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Goes in config/initializers/monkeypatches.rb | |
# Work around a Rails bug with literal %% in String interpolations. | |
# The bug exists in at least 2.3.5 and 3.0. | |
# https://rails.lighthouseapp.com/projects/8994/tickets/4052 | |
class String | |
alias :interpolate_without_ruby_19_syntax :% unless String.new.respond_to?(:interpolate_without_ruby_19_syntax) | |
INTERPOLATION_PATTERN = Regexp.union( | |
/%\{(\w+)\}/, # matches placeholders like "%{foo}" | |
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d" | |
) | |
INTERPOLATION_PATTERN_WITH_ESCAPE = Regexp.union( | |
/%%/, | |
INTERPOLATION_PATTERN | |
) | |
def %(args) | |
if args.kind_of?(Hash) | |
dup.gsub(INTERPOLATION_PATTERN_WITH_ESCAPE) do |match| | |
if match == '%%' | |
'%' | |
else | |
key = ($1 || $2).to_sym | |
raise KeyError unless args.has_key?(key) | |
$3 ? sprintf("%#{$3}", args[key]) : args[key] | |
end | |
end | |
elsif self =~ INTERPOLATION_PATTERN | |
raise ArgumentError.new('one hash required') | |
else | |
result = gsub(/%([{<])/, '%%\1') | |
result.send :'interpolate_without_ruby_19_syntax', args | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment