Skip to content

Instantly share code, notes, and snippets.

@ozgun
Created December 9, 2015 16:53
Show Gist options
  • Save ozgun/e452d7741f2d145a0f34 to your computer and use it in GitHub Desktop.
Save ozgun/e452d7741f2d145a0f34 to your computer and use it in GitHub Desktop.
Custom Rails Responder for Service Objects
class Dashboard::Payments::CardsController < ::Dashboard::Payments::BaseController
self.responder = Core::CustomServiceResponder
respond_to :html
before_action :customer_required
def destroy
service = Payments::Stripe::DeleteCreditCard.new(current_user)
status_object = service.call(params[:identifier])
respond_with status_object, location: -> { dashboard_payments_cards_path }
end
def create
service = Payments::Stripe::AddCreditCard.new(current_user)
status_object = service.call(params[:stripeToken])
respond_with status_object, location: -> { dashboard_payments_cards_path }
end
end
module Core
# This responder is used with service objects.
#
# status_object = MyService.new.call
# respond_with status_object, location: -> { payments_cards_path }, another_option: 'Another option'
#
# 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 'result.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
translation_options = mount_i18n_options(status)
# message = Responders::FlashResponder.helper.t options[:default].shift, options
message = text_or_html_translation(translation_options[:default])
end
set_flash(status, message)
end
# Example for `translation_keys` parameter:
#
# [
# :"flash.dashboard.payments.cards.create.notice_html",
# :"flash.dashboard.payments.cards.create.notice",
# :"flash.actions.create.notice_html",
# :"flash.actions.create.notice",
# ""
# ]
#
def text_or_html_translation(translation_keys)
message = 'Translation not found!'
translation_keys.each do |translation_key|
begin
message = Responders::FlashResponder.helper.t(translation_key, raise: true)
return message
rescue I18n::MissingTranslationData
next
end
end
message
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment