Chris@909: module CodeRay Chris@909: Chris@909: # The result of a scan operation is a TokensProxy, but should act like Tokens. Chris@909: # Chris@909: # This proxy makes it possible to use the classic CodeRay.scan.encode API Chris@909: # while still providing the benefits of direct streaming. Chris@909: class TokensProxy Chris@909: Chris@909: attr_accessor :input, :lang, :options, :block Chris@909: Chris@909: # Create a new TokensProxy with the arguments of CodeRay.scan. Chris@909: def initialize input, lang, options = {}, block = nil Chris@909: @input = input Chris@909: @lang = lang Chris@909: @options = options Chris@909: @block = block Chris@909: end Chris@909: Chris@909: # Call CodeRay.encode if +encoder+ is a Symbol; Chris@909: # otherwise, convert the receiver to tokens and call encoder.encode_tokens. Chris@909: def encode encoder, options = {} Chris@909: if encoder.respond_to? :to_sym Chris@909: CodeRay.encode(input, lang, encoder, options) Chris@909: else Chris@909: encoder.encode_tokens tokens, options Chris@909: end Chris@909: end Chris@909: Chris@909: # Tries to call encode; Chris@909: # delegates to tokens otherwise. Chris@909: def method_missing method, *args, &blk Chris@909: encode method.to_sym, *args Chris@909: rescue PluginHost::PluginNotFound Chris@909: tokens.send(method, *args, &blk) Chris@909: end Chris@909: Chris@909: # The (cached) result of the tokenized input; a Tokens instance. Chris@909: def tokens Chris@909: @tokens ||= scanner.tokenize(input) Chris@909: end Chris@909: Chris@909: # A (cached) scanner instance to use for the scan task. Chris@909: def scanner Chris@909: @scanner ||= CodeRay.scanner(lang, options, &block) Chris@909: end Chris@909: Chris@909: # Overwrite Struct#each. Chris@909: def each *args, &blk Chris@909: tokens.each(*args, &blk) Chris@909: self Chris@909: end Chris@909: Chris@909: end Chris@909: Chris@909: end