Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

draft

  • Loading branch information...
commit 5f20de3d5663a7307411e59897df6bd037a36ec7 1 parent 05a2e32
@kachick authored
Showing with 44 additions and 38 deletions.
  1. +44 −38 lib/sugarparser.rb
View
82 lib/sugarparser.rb
@@ -6,6 +6,47 @@
class SugarParser
class ParsingError < RuntimeError; end
+
+ module ClassMethods
+
+ def parse(str)
+ new(str).run
+ end
+
+ end
+
+ module InstanceMethods
+
+ extend Forwardable
+
+ def_delegators :@scanner, :eos?, :rest, :rest?, :peek,
+ :scan, :check, :skip
+
+ def trim(rxp)
+ unless skip rxp
+ raise ParsingError, rest.lines.first
+ end
+ end
+
+ def must(rxp, &block)
+ unless try(rxp, &block)
+ raise ParsingError, rest.lines.first
+ end
+ end
+
+ def try(rxp, &block)
+ if scan rxp
+ block.call(* captures(block.arity))
+ end
+ end
+
+ private
+
+ def captures(length)
+ (0..length).map{|n|@scanner[n]}
+ end
+
+ end
class << self
@@ -13,56 +54,21 @@ def define(klass, &scenario)
Class.new(self).tap do |concrete|
concrete.class_eval do
- extend Forwardable
-
- singleton_class.class_eval do
-
- def parse(str)
- new(str).run
- end
-
- end
+ extend ClassMethods
+ include InstanceMethods
define_method :initialize do |str|
- @result = klass.new
+ @result = klass.new
@scanner = StringScanner.new str
end
- def_delegators :@scanner, :eos?, :rest, :rest?, :peek,
- :scan, :check, :skip
-
define_method :run do
instance_exec @result, &scenario
raise ParsingError unless eos?
@result
end
- def trim(rxp)
- unless skip rxp
- raise ParsingError, rest.lines.first
- end
- end
-
- def must(rxp, &block)
- unless try(rxp, &block)
- raise ParsingError, rest.lines.first
- end
- end
-
- def try(rxp, &block)
- if scan(rxp)
- block.call(* captures(block.arity))
- end
- end
-
- private
-
- def captures(length)
- (0..length).map{|n|@scanner[n]}
- end
-
end
-
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.