Skip to content

Instantly share code, notes, and snippets.

@henrik
Created February 25, 2010 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrik/314504 to your computer and use it in GitHub Desktop.
Save henrik/314504 to your computer and use it in GitHub Desktop.
# 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