Skip to content

Instantly share code, notes, and snippets.

@ajuckel
Created September 20, 2011 13:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ajuckel/1229071 to your computer and use it in GitHub Desktop.
Quick implementation of hash format for jruby
# Not sure where this is defined in MRI, but appeared to be missing in JRuby
if defined?(JRUBY_VERSION) && RUBY_VERSION =~ /^1\.9/
class KeyError < IndexError
end
class String
alias_method :old_format, :%
def %(replacements)
split_re = /(?<!%)(%{[^}]+})/
replace_re = /(?<!%)%{([^}]+)}/
if ! replacements.is_a? Hash
if split_re.match self
raise ArgumentError, "one hash required"
else
return self.old_format replacements
end
end
segments = self.split split_re
segments.each_index do |i; md, key|
md = replace_re.match(segments[i])
if ! md.nil?
key = md.captures[0].to_sym
raise KeyError, "key[#{key}] not found" unless replacements.has_key?(key)
segments[i] = replacements[key]
else
segments[i] = segments[i].gsub "%%", "%"
end
end
segments.join
end
end
end
describe "String modulo operator" do
before {
@hash = { foo: 'oof', bar: 'rab', baz: 'zab' }
@cases = [ ["%{foo}", 'oof'],
["%{foo} %{foo}", 'oof oof'],
["%%{foo}", "%{foo}"],
[" %{foo} %{bar} text\n%{baz} ", " oof rab text\nzab " ]
]
}
it "should handle our expected test cases" do
@cases.each_index do |c|
(@cases[c][0] % @hash).should == @cases[c][1]
end
end
it "should raise KeyError if key is missing" do
lambda {"%{foo}" % {}}.should raise_error(KeyError)
end
it "should raise ArgumentError if no hash given" do
lambda {"%{foo}" % []}.should raise_error(ArgumentError)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment