Skip to content

Commit

Permalink
Raising Error if book abbreviation is ambiguous, some refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
janfri committed May 21, 2015
1 parent 25b2767 commit 1303ffc
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 9 deletions.
30 changes: 22 additions & 8 deletions lib/scripref/parser.rb
Expand Up @@ -37,7 +37,7 @@ def start
def b1
s = scan(book_re) or return nil
@text << s
@b1 = @b2 = book2num(s)
@b1 = @b2 = abbrev2num(s)

if check(Regexp.new(NUMBER_RE.source + cv_sep_re.source))
@c1 = @v1 = nil
Expand Down Expand Up @@ -107,7 +107,7 @@ def v1
def b2
s = scan(book_re) or return nil
@text << s
@b2 = book2num(s)
@b2 = abbrev2num(s)
@c2 = @v2 = nil

if check(Regexp.new(NUMBER_RE.source + cv_sep_re.source))
Expand Down Expand Up @@ -224,14 +224,26 @@ def push_passage
@a1 = @a2 = nil
end

def abbrev2num str
book2num(abbrev2book(str))
end

def abbrev2book str
@books_str ||= ('#' << book_names.join('#') << '#')
pattern = str.strip.each_char.map {|c| c << '[^#]*'}.join
pattern.gsub!('.', '\\.')
re = /(?<=#)#{pattern}(?=#)/
names = @books_str.scan(re)
fail Error, format("Abbreviation %s is ambiguous it matches %s!", str, names.join(', ')) unless names.size == 1
names.first
end

def book2num str
return nil unless book_re =~str
books_res.each_with_index do |re, i|
if str =~ Regexp.new('^' << re.to_s << '$')
num = i + 1
return num
end
unless @book2num
@book2num = {}
book_names.each_with_index {|s, i| @book2num[s] = i+1}
end
@book2num[str]
end

def inspect
Expand All @@ -240,6 +252,8 @@ def inspect

alias << parse

class Error < RuntimeError; end

end

end
1 change: 0 additions & 1 deletion test/test_english.rb
Expand Up @@ -29,7 +29,6 @@ def test_book2num
assert_book_num 66, 'Revelation'
assert_book_num 1, 'Gen'
assert_book_num 1, 'Ge'
assert_book_num 1, 'G'
assert_book_num 55, '2 Tim'
assert_book_num 55, '2Tim'
assert_book_num 55, '2Tm'
Expand Down
11 changes: 11 additions & 0 deletions test/test_parser.rb
Expand Up @@ -16,6 +16,17 @@ def test_only_book
assert_parsed_ast_for_text [pass(text, 8, nil, nil, 8, nil, nil)], text
end

def test_ambiguous_book
assert_raises Scripref::Parser::Error do
begin
@parser.parse 'Jo'
rescue RuntimeError => e
assert_equal 'Abbreviation Jo is ambiguous it matches Josua, Joel, Jona, Johannes, Jakobus!', e.message
raise e
end
end
end

def test_book_and_chapter
text = 'Ruth 2'
assert_parsed_ast_for_text [pass(text, 8, 2, nil, 8, 2, nil)], text
Expand Down

0 comments on commit 1303ffc

Please sign in to comment.