Skip to content

Instantly share code, notes, and snippets.

@sgronblo
Created February 27, 2012 07:12
Show Gist options
  • Save sgronblo/1922157 to your computer and use it in GitHub Desktop.
Save sgronblo/1922157 to your computer and use it in GitHub Desktop.
Indented puts Ruby Module, just include and go. You can also change the indentation size.
class IndentedPutser
attr_accessor :level
def initialize(size)
@level = 0
@size = size
end
def indent
self.level += 1
yield self
self.level -= 1
end
def puts(message)
if !message.is_a?(String) && message.respond_to?(:to_s)
message = message.to_s
end
Kernel.puts((' ' * @size * level) + message)
end
end
module Indentation
def indent(indentation_size = 3, &block)
IndentedPutser.new(indentation_size).indent &block
end
end
# example usage
indent do |i|
i.puts 'level 1'
i.indent do |i|
i.puts 'level 2'
end
end
@sgronblo
Copy link
Author

The previous version messed up the binding to puts after being called

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment