module AttributeReadAuthorized
  extend ActiveSupport::Concern

  # Takes a Service::Base object nils out any attributes a user is not
  # authorized to view. Additionally sets errors on the object using rails
  # errors: https://api.rubyonrails.org/classes/ActiveModel/Errors.html
  #
  # Works well with ApplicationHelper.redact when rendering views.
  def redact_attributes(obj)
    (obj.class.attribute_syms - policy(obj).permitted_read_attributes)
      .each do |attr|
        obj.errors.add(attr, :not_authorized, message: 'Not authorized to view.')
        obj.send("#{attr}=", nil)
      end
    obj
  end
end
