Skip to content

Commit

Permalink
Yield created resource if block is given
Browse files Browse the repository at this point in the history
This creates an interface to allow you to trigger actions after a
resource has been created (for example, run a background job).

Whilst this was previously possible by utilising
`after_resource_created_path`, this is much more pleasant.
  • Loading branch information
trevorrjohn authored and nickcharlton committed Jan 17, 2024
1 parent 7d52893 commit 23472a3
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions app/controllers/administrate/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def create
authorize_resource(resource)

if resource.save
yield(resource) if block_given?
redirect_to(
after_resource_created_path(resource),
notice: translate_with_resource("create.success"),
Expand Down
14 changes: 14 additions & 0 deletions docs/customizing_controller_actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,17 @@ To set custom redirects after the actions `create`, `update` and `destroy` you c
[namespace, requested_resource.some_other_resource]
end
```

## Creating Records

You can perform actions after creation by passing a `block` to `super` in the
`create` method. The block will only be called if the resource is successfully
created.

```ruby
def create
super do |resource|
# do something with the newly created resource
end
end
```
27 changes: 27 additions & 0 deletions spec/controllers/admin/application_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,33 @@ def after_resource_updated_path(requested_resource)
end
end

describe "creation yeilds resource" do
controller(Admin::OrdersController) do
attr_reader :resource

def create
super do |resource|
@resource = resource
end
end
end

it "yields the created resource after creation" do
customer = create(:customer)
order_attributes = build(:order, customer: customer).attributes
params = order_attributes.except(
"id",
"created_at",
"updated_at",
"shipped_at",
)

post :create, params: { order: params }

expect(controller.resource).to be_a(Order)
end
end

describe "authorization" do
controller(Administrate::ApplicationController) do
def resource_class
Expand Down

0 comments on commit 23472a3

Please sign in to comment.