diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep deleted file mode 100644 index e69de29b..00000000 diff --git a/app/controllers/concerns/turbo_streamable.rb b/app/controllers/concerns/turbo_streamable.rb new file mode 100644 index 00000000..694b4a7c --- /dev/null +++ b/app/controllers/concerns/turbo_streamable.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +module TurboStreamable + extend ActiveSupport::Concern + + included do |controller| + around_action :handle_error, only: controller.respond_to?(:turbo_stream_actions) ? controller.turbo_stream_actions : [] + end + + def render_toast(message, success = true) + turbo_stream.append("toasts", partial: "shared/toast", locals: { message:, success: }) + end + + class_methods do + def render_toast = render_toast + end + + private + + def handle_error + yield + rescue Errors::Base => e + render_error I18n.t(e.locale_tag) + rescue KeyError, ActionController::ParameterMissing => e + render_error t("errors.parameter_error", parameter: e.is_a?(KeyError) ? e.key : e.param.capitalize) + rescue Dry::Types::CoercionError, Dry::Types::ConstraintError + render_error t("errors.invalid_parameter") + rescue ActiveRecord::RecordNotFound + render_error t("errors.record_not_found") + end + + def render_error(message) + respond_to do |format| + format.turbo_stream do + render turbo_stream: render_toast(message, false) + end + end + end +end diff --git a/app/views/layouts/base.html.haml b/app/views/layouts/base.html.haml index d1d7d54a..edbd026e 100644 --- a/app/views/layouts/base.html.haml +++ b/app/views/layouts/base.html.haml @@ -31,6 +31,7 @@ = render 'shared/announcements' = yield = render "shared/formatting" + #toasts.d-none - if Rails.env.development? #debug %hr diff --git a/app/views/shared/_toast.html.haml b/app/views/shared/_toast.html.haml new file mode 100644 index 00000000..de241ebd --- /dev/null +++ b/app/views/shared/_toast.html.haml @@ -0,0 +1 @@ +.d-none{ data: { controller: "toast", toast_message_value: message, toast_success_value: success } }