When talking about declarative transactions at Ginza Ruby Conference 01, @a_matsuda doesn't want Rails to have declarative transactions? I was saying something like that, so I made it quickly with gem.
https://github.com/ttanimichi/transactional
A declarative transaction is a method of declaratively describing that a transaction is automatically executed when a method is called. Java's Spring Framework is a well-known implementation framework. For Spring Framework, you can use declarative transactions by annotating methods with @Transactional
.
@Transactional
public void create(int id) {
// do something
}
Add it to your Gemfile and do a bundle install.
gem 'transactional'
All you have to do now is specify in transactional
the action you want to make a transaction with in Controller.
class YourController < ApplicationController
+ transactional :create, :update
+
def index
end
def create
Post.create!(name: 'john', age: 42)
Topic.create!(title: 'invalid title')
render plain: :created
end
def update
end
end
Will automatically take a transaction when the specified action is called.
Processing by YourController#create as HTML
(0.2ms) BEGIN
SQL (0.5ms) INSERT INTO "posts" ("name", "age", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["name", "john"], ["age", 42], ["created_at", "2017-08-06 08:23:13.980493"], ["updated_at", "2017-08-06 08:23:13.980493"]]
(0.2ms) ROLLBACK
In this example, you can see that the posts INSERT is rolled back when Topic's create! Throws an exception.
Recommended Posts