Skip to content

Commit

Permalink
Add a GrammarMethods#parse_file method.
Browse files Browse the repository at this point in the history
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
blambeau committed Feb 22, 2012
1 parent e23958e commit 0fb17d1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/citrus.rb
Expand Up @@ -395,6 +395,16 @@ def parse(string, options={})
rule.parse(string, options) rule.parse(string, options)
end 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. # Returns the name of this grammar as a string.
def name def name
super.to_s super.to_s
Expand Down
23 changes: 23 additions & 0 deletions test/grammar_test.rb
Expand Up @@ -126,6 +126,29 @@ def test_parse_recurs
assert_equal(str.length, match.length) assert_equal(str.length, match.length)
end 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 def test_global_grammar
assert_raise ArgumentError do assert_raise ArgumentError do
grammar(:abc) grammar(:abc)
Expand Down

0 comments on commit 0fb17d1

Please sign in to comment.