Quick implementation of hash format for jruby
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
# 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