Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add a GrammarMethods#parse_file method.

While the parse method already accepts Pathname instances and the
like, some users might prefer making explicit the fact that they
want to parse from a file. A Pathname instance is automatically
created if needed.
  • Loading branch information...
commit 0fb17d1f38efab148a1433eb16c4016e8db2d6bb 1 parent e23958e
@blambeau blambeau authored
Showing with 33 additions and 0 deletions.
  1. +10 −0 lib/citrus.rb
  2. +23 −0 test/grammar_test.rb
View
10 lib/citrus.rb
@@ -395,6 +395,16 @@ def parse(string, options={})
rule.parse(string, options)
end
+ # Parse the given file at +path+ using this grammar's root role. Accept the same
+ # +options+ as #parser.
+ def parse_file(path, options = {})
+ unless path.respond_to?(:to_path)
+ require 'pathname'
+ path = Pathname.new(path)
+ end
+ parse(path, options)
+ end
+
# Returns the name of this grammar as a string.
def name
super.to_s
View
23 test/grammar_test.rb
@@ -126,6 +126,29 @@ def test_parse_recurs
assert_equal(str.length, match.length)
end
+ def test_parse_file
+ grammar = Grammar.new {
+ rule("words"){ rep(any(" ", /[a-z]+/)) }
+ }
+
+ require 'tempfile'
+ Tempfile.open('citrus') do |tmp|
+ tmp << "abd def"
+ tmp.close
+
+ match = grammar.parse_file(tmp.path)
+
+ assert(match)
+ assert_instance_of(Input, match.input)
+ assert_instance_of(Pathname, match.source)
+
+ match.matches.each do |m|
+ assert_instance_of(Input, m.input)
+ assert_instance_of(Pathname, m.source)
+ end
+ end
+ end
+
def test_global_grammar
assert_raise ArgumentError do
grammar(:abc)
Please sign in to comment.
Something went wrong with that request. Please try again.