Ruby - Take off delegator/decorator

06 Sep 2020

You will see the decorator which implemented with SimpleDelegator in Ruby like this:

class UserDecorator < SimpleDelegator
end

user_presenter = UserDecorator.new(user)

But sometimes you may want to take off the decorator/delegator and get the original object. We have a simple way to do it in the Ruby. It’s __getobj__:

module CanTakeOffDecorator
  extend ActiveSupport::Concern

  included do
    def take_off_decorator
      __getobj__
    end
  end
end

class UserDecorator < SimpleDelegator
  include CanTakeOffDecorator
end

user_presenter = UserDecorator.new(user)

Now we can take off the decorator like this:

user_presenter.take_off_decorator
Back to top