Skip to content

Commit

Permalink
Introduced Grammar.create()
Browse files Browse the repository at this point in the history
  • Loading branch information
yanivmo committed Jun 4, 2017
1 parent 2fe060c commit d0e0af5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 17 deletions.
18 changes: 6 additions & 12 deletions src/ruler/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,22 @@
class Grammar(object):
grammar = None

def __init__(self):
self.matched = None
self.error = None

@classmethod
def create(cls):
# Collect and name member rules
for attr_name in dir(self):
for attr_name in dir(cls):

# 'grammar' is a reserved name
if attr_name == 'grammar':
continue

attr = self.__getattribute__(attr_name)
attr = getattr(cls, attr_name)
if isinstance(attr, BaseRule):
attr.name = attr_name

self.grammar.register_named_subrules()
cls.grammar.register_named_subrules()

def match(self, text):
result = self.grammar.match(text)
self.matched = self.grammar.matched
self.error = self.grammar.error
return result
return cls.grammar


class CompoundRule(BaseCompoundRule):
Expand Down
10 changes: 5 additions & 5 deletions tests/test_ruler.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class G(Grammar):
e = Rule('e')
grammar = Rule('a', bcd, e)

g = G()
g = G.create()

assert g.match('abcde')
assert g.matched == 'abcde'
Expand Down Expand Up @@ -212,19 +212,19 @@ def test_example(self):
milk = 'with milk'
"""

class Morning(Grammar):
class MorningGrammar(Grammar):
who = OneOf('John', 'Peter', 'Ann')
juice = Rule('juice')
milk = Optional(' with milk')
tea = Rule('tea', milk)
what = OneOf(juice, tea)
grammar = Rule(who, ' likes to drink ', what, '\.')

r = Morning()
r = MorningGrammar.create()

assert r.juice.name == 'juice'
assert MorningGrammar.juice.name == 'juice'
with raises(RuleNamingError):
r.juice.name = ''
MorningGrammar.juice.name = ''

assert r.match('Ann likes to drink tea with milk.')
assert r.who.matched == 'Ann'
Expand Down

0 comments on commit d0e0af5

Please sign in to comment.