lib/hexapdf/content/parser.rb in hexapdf-0.11.9 vs lib/hexapdf/content/parser.rb in hexapdf-0.12.0
- old
+ new
@@ -2,11 +2,11 @@
#
#--
# This file is part of HexaPDF.
#
# HexaPDF - A Versatile PDF Creation and Manipulation Library For Ruby
-# Copyright (C) 2014-2019 Thomas Leitner
+# Copyright (C) 2014-2020 Thomas Leitner
#
# HexaPDF is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3 as
# published by the Free Software Foundation with the addition of the
# following permission added to Section 15 as permitted in Section 7(a):
@@ -160,15 +160,28 @@
# To parse some contents the #parse method needs to be called with the contents to be parsed
# and a Processor object which is used for processing the parsed operators.
class Parser
# Creates a new Parser object and calls #parse.
- def self.parse(contents, processor)
- new.parse(contents, processor)
+ def self.parse(contents, processor = nil, &block)
+ new.parse(contents, processor, &block)
end
- # Parses the contents and calls the processor object for each parsed operator.
- def parse(contents, processor)
+ # Parses the contents and calls the processor object or the given block for each parsed
+ # operator.
+ #
+ # If a full-blown Processor is not needed (e.g. because the graphics state doesn't need to be
+ # maintained), one can use the block form to handle the parsed objects and their parameters.
+ #
+ # Note: The parameters array is reused for each processed operator, so duplicate it if
+ # necessary.
+ def parse(contents, processor = nil, &block) #:yields: object, params
+ raise ArgumentError, "Argument processor or block is needed" if processor.nil? && block.nil?
+ if processor.nil?
+ block.singleton_class.alias_method(:process, :call)
+ processor = block
+ end
+
tokenizer = Tokenizer.new(contents, raise_on_eos: true)
params = []
loop do
obj = tokenizer.next_object(allow_keyword: true)
if obj.kind_of?(Tokenizer::Token)