Sha256: 94b29bcdeea5fc54af235f268159025ee44826c4d888906fa1936a8634e7daf0

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 KB

Contents

module ExpressTemplates

  # Tracks current indent level scoped to the current thread.
  #
  # May be used to track multiple indents simultaneously through
  # namespacing.
  class Indenter

    DEFAULT = 2
    WHITESPACE = " "*DEFAULT

    # Returns whitespace for the named indenter or yields to a block
    # for the named indentor.
    #
    # The block is passed the current whitespace indent.
    #
    # For convenience an optional second parameter is passed to the block
    # containing a newline at the beginning of the indent.
    def self.for name
      if block_given?
        current_indenters[name] += 1
        begin
          indent = WHITESPACE * current_indenters[name]
          yield indent, "\n#{indent}"
        ensure
          current_indenters[name] -= 1
          # if we have long-lived threads for some reason
          # we want to clean up after ourselves
          current_indenters.delete(name) if current_indenters[name].eql?(0)
        end
      else
        return WHITESPACE * current_indenters[name]
      end
    end

    private
      # For thread safety, scope indentation to the current thread
      def self.current_indenters
        Thread.current[:indenters] ||= Hash.new {|hsh, key| hsh[key] = 0 }
      end

  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
express_templates-0.2.7 lib/express_templates/indenter.rb
express_templates-0.2.6 lib/express_templates/indenter.rb
express_templates-0.2.5 lib/express_templates/indenter.rb
express_templates-0.2.4 lib/express_templates/indenter.rb
express_templates-0.2.3 lib/express_templates/indenter.rb
express_templates-0.2.2 lib/express_templates/indenter.rb