Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created November 10, 2021 08:59
Show Gist options
  • Save julianrubisch/57237a9f87e016647f04ff0b40a2631d to your computer and use it in GitHub Desktop.
Save julianrubisch/57237a9f87e016647f04ff0b40a2631d to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
include Pundit
end
# app/reflexes/application_reflex.rb
class ApplicationReflex < StimulusReflex::Reflex
include Pundit
rescue_from Pundit::NotAuthorizedError do |exception|
cable_ready
.inner_html(selector: "#alert", html: exception.message)
.remove_css_class(name: "hidden")
.broadcast
end
delegate :current_user, to: :connection
end
class ApplicationReflex < StimulusReflex::Reflex
include Pundit
delegate :current_user, to: :connection
end
$ bundle add pundit
$ bin/rails g pundit:install
import ApplicationController from "./application_controller";
export default class extends ApplicationController {
connect() {
super.connect();
}
destroyHalted() {
alert("You are not allowed to destroy this embed!");
}
}
<!-- app/view/embeds/_embed.html.erb -->
<%= link_to "#", class: "absolute top-0 right-0 m-2", data: {
reflex: "click->Embed#destroy",
reflex_dataset: "ancestors"
} do %>
<i class="fas fa-times text-gray-400"></i>
<% end %>
# app/policies/embed_policy.rb
class EmbedPolicy < ApplicationPolicy
attr_reader :user, :embed
def initialize(user, embed)
@user = user
@embed = embed
end
def destroy?
embed.board.owner == user
end
end
# app/reflexes/embed_reflex.rb
class EmbedReflex < ApplicationReflex
# ...
before_reflex only: [:destroy, :update] do
@embed = element.signed[:sgid]
throw :abort unless policy(@embed).send("#{action_name}?")
end
# ...
end
# app/reflexes/embed_reflex.rb
class EmbedReflex < ApplicationReflex
# ...
before_reflex only: :destroy do
@embed = element.signed[:sgid]
throw :abort unless policy(@embed).destroy?
end
# ...
end
# app/reflexes/embed_reflex.rb
class EmbedReflex < ApplicationReflex
# ...
def destroy
@embed = element.signed[:sgid]
authorize @embed # <= here
@embed.destroy
end
end
# app/reflexes/embed_reflex.rb
class EmbedReflex < ApplicationReflex
# ...
def destroy
@embed = element.signed[:sgid]
@embed.destroy
end
end
$ bin/rails g pundit:policy embed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment