Sha256: fd0f35a4b26c9b7a9b9920067f62c533eda8b0c84644e71625975722ea6bc599

Contents?: true

Size: 1.68 KB

Versions: 7

Compression:

Stored size: 1.68 KB

Contents

module SXP
  ##
  # An S-expression generator.
  class Generator
    ##
    # @param  [Array]  sxps
    # @return [Object]
    def self.string(*sxps)
      require 'stringio' unless defined?(StringIO)
      write(StringIO.new, *sxps).instance_variable_get('@buffer').string
    end

    ##
    # @param  [Array]  sxps
    # @return [Object]
    def self.print(*sxps)
      write($stdout, *sxps)
    end

    ##
    # @param  [Object] out
    # @param  [Array]  sxps
    # @return [Object]
    def self.write(out, *sxps)
      generator = self.new(out)
      sxps.each do |sxp|
        generator.send((op = sxp.shift).to_sym, *sxp)
      end
      generator
    end

    ##
    # @param  [Object] buffer
    def initialize(buffer)
      @output = [@buffer = buffer]
      @indent = 0
    end

    protected

    ##
    # @param  [String]                 text
    # @param  [Hash{Symbol => Object}] options
    # @return [void]
    def emit(text, options = {})
      if out = @output.last
        out.print(' ' * (indent * 2)) if options[:indent]
        out.print(text)
      end
    end

    ##
    # @yield
    # @return [String]
    def captured(&block)
      require 'stringio' unless defined?(StringIO)
      begin
        @output.push(buffer = StringIO.new)
        block.call
      ensure
        @output.pop
      end
      buffer.string
    end

    ##
    # @yield
    # @return [Object]
    def indented(&block)
      begin
        increase_indent!
        block.call
      ensure
        decrease_indent!
      end
    end

    ##
    # @return [void]
    def increase_indent!
      @indent += 1
    end

    ##
    # @return [void]
    def decrease_indent!
      @indent -= 1
    end
  end # Generator
end # SXP

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
sxp-0.0.14 lib/sxp/generator.rb
sxp-0.0.13 lib/sxp/generator.rb
sxp-0.0.12 lib/sxp/generator.rb
sxp-0.0.11 lib/sxp/generator.rb
sxp-0.0.10 lib/sxp/generator.rb
sxp-0.0.9 lib/sxp/generator.rb
sxp-0.0.8 lib/sxp/generator.rb