Skip to content

Instantly share code, notes, and snippets.

@adrianotadao
Created July 30, 2015 20:35
Show Gist options
  • Save adrianotadao/7ee49334a2f7d2a3dd30 to your computer and use it in GitHub Desktop.
Save adrianotadao/7ee49334a2f7d2a3dd30 to your computer and use it in GitHub Desktop.

#Models

####Abstration & Transitions

Obs: Quando usamos o: self.class.transaction do, isso faz com que as inserções no banco de dados sejam feitas atomicamente. Se alguma das linhas der fail o banco de dados faz rollback em tudo o que estiver dentro do bloco.

errado:

#app/controllers/users_controller.rb
class UsersController < ApplicationController
	def suspend
		@user = User.find(params[:id])
		@user.suspend!
		redirect_to @user
	end
end

#app/models/user.rb
class User < ActiveRecord::Base
	has_many :items
	has_many :reviews
	
	def suspend!
		self.class.transaction do
			self.update!(is_approved: false)
			self.items.each{ |item| item.update!(is_approved: false )}
			self.reviews.each{ |review| review.update!(is_approved: false )}
		end
	end
end

correto:

#app/models/user_suspension.rb
class UserSuspension
	def initialize(user)
		@user = user
	end
	
	def create
		@user.class.transaction do
			disapprove_user!
			disapprove_items!
			disapprove_reviews!
		end
	end
	
	private
	def disapprove_user!
		@user.update!(is_approved: false)
	end
	
	def disapprove_items!
		@user.items.each{ |item| item.update!(is_approved: false )}
	end
	
	def disapprove_reviews!
		@user.reviews.each{ |review| review.update!(is_approved: false )}
	end
	
end

#app/controllers/users_controller.rb
class UsersController < ApplicationController
	def suspend
		@user = User.find(params[:id])
		suspension = UserSuspension.new(@user)
		suspension.create!
		redirect_to @user
	end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment