Skip to content

Commit

Permalink
Improve enfore_modal method and rescue from it (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-nerdgeschoss authored Oct 10, 2024
1 parent 96a59bf commit eca1c2e
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,12 @@ a href=popover_path(new_post_path, placement: :left)

This will request `new_post_path` and display it left of the anchor thanks to PopperJS.

> [!TIP]
> If you want to make sure that your modal content is only available if requested through Shimmer, you can use the built in `enfore_modal` method as a `before_action`. It will return a _422 Unprocessable Content_ status if users (or bots) access the page directly.
> ```rb
> before_action :enforce_modal, only: [:popover]
> ```

### Remote Navigation

Remote navigation takes Hotwire to the next level with built-in navigation actions, integrated with modals and popovers.
Expand Down
14 changes: 13 additions & 1 deletion lib/shimmer/utils/remote_navigation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ module Shimmer
module RemoteNavigation
extend ActiveSupport::Concern

class RemoteNavigationError < StandardError; end

included do
def ui
@ui ||= RemoteNavigator.new(self)
Expand Down Expand Up @@ -45,7 +47,17 @@ def render_modal
end

def enforce_modal
raise "trying to render a modal from a regular request" unless shimmer_request?
return if shimmer_request?

raise RemoteNavigationError.new("You may only render a modal from a Shimmer request.")
end

rescue_from RemoteNavigationError do |exception|
if Rails.env.development?
render plain: exception.message, status: :unprocessable_entity
else
head :unprocessable_entity
end
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/rails_app/app/controllers/posts_controller.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true

class PostsController < ApplicationController
before_action :enforce_modal, only: [:modal]

def index
@posts = Post.all
end
Expand All @@ -18,6 +20,9 @@ def create
end
end

def modal
end

private

def post_params
Expand Down
6 changes: 5 additions & 1 deletion spec/rails_app/config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

Rails.application.routes.draw do
resources :files, only: :show, controller: "shimmer/files"
resources :posts
resources :posts do
collection do
get :modal
end
end

get "styleguide", to: "pages#styleguide"
root "posts#index"
Expand Down

0 comments on commit eca1c2e

Please sign in to comment.