Skip to content

Instantly share code, notes, and snippets.

@mikesive
Created November 13, 2017 19:13
Show Gist options
  • Save mikesive/bc9e7d9229259f929e8192461f2b00bc to your computer and use it in GitHub Desktop.
Save mikesive/bc9e7d9229259f929e8192461f2b00bc to your computer and use it in GitHub Desktop.
module Interactable
extend ActiveSupport::Concern
included do
around_action :format_interactor_response
end
private
def format_interactor_response
result = yield
# No-op if we haven't returned an interactor context
return result unless result.is_a?(Interactor::Context)
# Determine http status
default_status = result.success? ? 200 : 400
status = result.http_status || default_status
# Extract the response data from interactor result
data = format_response_data(result.data, result.success?)
render json: data, status: status
end
# If the data is a string, wrap it in a hash
# Otherwise return the data as-is
def format_response_data(data, success)
data.is_a?(String) ? { message: data } : data
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment