Skip to content

Instantly share code, notes, and snippets.

@raphink
Created September 4, 2014 08:09
Show Gist options
  • Save raphink/4bcdb7c2291e8db88175 to your computer and use it in GitHub Desktop.
Save raphink/4bcdb7c2291e8db88175 to your computer and use it in GitHub Desktop.
class String
old_format = instance_method(:%)
define_method(:%) do |arg|
return self unless self =~ /%/
if arg.is_a?(Hash)
(self.gsub(/%\{([^%]*?)\}/) {
a = $1
if a =~ /([^\[]+)\[([^\]]*)\](.*)/
h = arg[$1.to_sym][$2.to_sym]
h_args = $3.gsub(/\[([^:\]][^\]]*)\]/, '[:\1]')
h_args.nil? ? h : eval("h#{h_args}")
else
arg[a.to_sym]
end
}) % arg
else
old_format.bind(self).call(arg)
end
end
end
puts '%{a}, %{b[%{id}][:d]}' % { :a => 'hello', :b => { :c => { :d => 'world' } }, :id => 'c' }
puts '%{a}, %{b[%{id}][d]}' % { :a => 'hello', :b => { :c => { :d => 'world' } }, :id => 'c' }
puts '%{a}, %{b}' % { :a => 'hello', :b => 'world' }
puts '%{a}, %{b[id]}' % { :a => 'hello', :b => { :id => 'world' } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment