Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resource instance variables and audit log sample #2478

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions app/controllers/administrate/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def index
resources = apply_collection_includes(resources)
resources = order.apply(resources)
resources = paginate_resources(resources)
@resources = resources
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be available through the locals (see lines 14-19). What use case do you have where that's not enough?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For consistency. Since I made @requested_resource and @new_resource as instance variables, I made it so that @resources can also be referenced from instance variables.

page = Administrate::Page::Collection.new(dashboard, order: order)

render locals: {
Expand All @@ -26,7 +27,7 @@ def show
end

def new
resource = new_resource
@new_resource = resource = new_resource
authorize_resource(resource)
render locals: {
page: Administrate::Page::Form.new(dashboard, resource),
Expand All @@ -40,7 +41,7 @@ def edit
end

def create
resource = new_resource(resource_params)
@new_resource = resource = new_resource(resource_params)
authorize_resource(resource)

if resource.save
Expand Down
17 changes: 17 additions & 0 deletions spec/example_app/app/controllers/admin/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,22 @@ def authenticate_admin
def pundit_user
@current_user
end

after_action :audit_log, only: %i[create update destroy]

def audit_log
if resource = @requested_resource || @new_resource
Rails.logger.info(
sprintf(
"Audit Log: %<action>s %<class>s #%<id>d by %<user>s at %<time>s",
action: action_name.capitalize,
class: resource.class,
id: resource.id || 0,
user: pundit_user.name,
time: Time.zone.now.to_s,
),
)
end
end
end
end