Wrote an indented printer, can it be made cleaner?

Hello I wrote the following module + class that can be used by including
in Object for example to get access to indent, which contains a special
version of puts that takes the current indentation level into account.
The end result worked on my small use case. It probably contains bugs.
But I was mainly interested in whether it can be rewritten. Especially
the method_missing seems kinda ugly to me. I had trouble when I wanted
to make it smooth to use by not having an explicit block variable,
instead relying on instance_exec. However if your block tries to call
anything from the original context it fails. Which is why I have to
extract the binding and eval the failed expressions from that.

class IndentedPutser
attr_accessor :level

def initialize(size, original_binding)
@level = 0
@size = size
@original_binding = original_binding
end

def indent(&block)
self.level += 1
self.instance_exec &block
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

def method_missing(symbol, *args)
@original_binding.eval("#{symbol}(#{args})")
end
end

module Indentation
def indent(indentation_size = 3, &block)
IndentedPutser.new(indentation_size, block.binding).indent &block
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs