One of the coolest techniques for writing structured code is to use a decorator. Ruby has a Delegator class, a DelegateClass method and a simple delegation implementation SimpleDelegator. If you are really interested in their implementation, you can find the source code here (https://github.com/ruby/delegate/blob/master/lib/delegate.rb).
A few weeks ago I had the task of making the output of a long exception message more concise, namely, making the message that was printed to the console a little shorter. The logic for modifying the message was implemented in the decorator class. Also, in order for the decorated object to introduce itself as the original exception, it was necessary to remove the definition of the class, instance_of?, kind_of? methods.
You can see a full example of the decorator and its use in the image.
How often do you use the delegate from the Ruby standard library?
require 'delegate'
class PrettyException < SimpleDelegator
undef_method :class
undef_method :instance_of?
undef_method :kind_of?
def message
"#{__getobj__.message.slice(0, 10)}..."
end
end
begin
# something went wrong
raise RuntimeError, 'some error, very long error description'
rescue StandardError => e
e = PrettyException.new(e)
puts "#{e.class.name}: #{e.message}"
end
# RuntimeError: some error...