Skip to content

Instantly share code, notes, and snippets.

@ozgun
Created June 23, 2015 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozgun/87e8092bae6b22964ad8 to your computer and use it in GitHub Desktop.
Save ozgun/87e8092bae6b22964ad8 to your computer and use it in GitHub Desktop.
Custom Responder for Service Objects
module MyModule
# This responder can be used with service objects.
#
# result = MyService.new.call
# respond_with result, location: -> { payments_cards_path }
#
# Assumption: When we call the service, we get a status/response object which responds to `success?` method.
# If response is successful, then the response object also responds to `data` method. If response is a
# failure, the response object responds to `error` method.
#
# If the response is not a successful response, we also set flash(alert) message, using response object's `error` method.
#
# Since 'result' is not an ActiveRecord::Base object, we have to define a
# location with 'location' parameter.
#
class CustomServiceResponder < ActionController::Responder
include Responders::FlashResponder
include Responders::HttpCacheResponder
private
def display(resource, options = {})
super(resource.data, options)
end
def has_errors?
!resource.success?
end
# set_flash_message! is overriden to use 'resource.error' method.
def set_flash_message!
if has_errors?
status = Responders::FlashResponder.flash_keys.last
set_flash(status, @alert)
else
status = Responders::FlashResponder.flash_keys.first
set_flash(status, @notice)
end
return if controller.flash[status].present?
if has_errors?
message = resource.error
else
options = mount_i18n_options(status)
message = Responders::FlashResponder.helper.t options[:default].shift, options
end
set_flash(status, message)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment