서비스를 사용하여 콜백을 피하는 방법.
4959 단어 callbackrefactoringrailsruby

종종 프로그래머는 콜백을 남용하여 결국 코드가 혼란스럽고 명확하지 않다는 것을 완전히 이해하지 못합니다. 콜백을 사용하지 않는 방법에는 여러 가지가 있습니다. 오늘은 서비스를 사용하여이를 수행하는 방법을 알려 드리겠습니다.
코드를 보자:
class User < ApplicationController
def create
@user = User.new(user_params)
if @user.save
redirect_to root_path, notice: "User created!"
else
render :new, error: 'Failed to create user!'
end
end
end
class User < ApplicationRecord
before_create :populate_serial_number
private
def populate_serial_number
self.serial_number ||= SecureRandom.uuid
end
end
이 코드의 문제점은 무엇입니까? 우리는 명백하지 않은(마법적인) 행동을 취합니다. 매개변수의 일련 번호에 대한 데이터를 전달하지 않으며 이 값을 어디에도 명시적으로 설정하지 않습니다. 이는 콜백과 함께 자동으로 발생합니다.
서비스를 사용하여 같은 것을 구현해 봅시다.
class CreateUser
def self.call(params)
@user = User.new(params)
populate_serial_number(@user)
# Other actions for the user
user.save!
end
def self.populate_serial_number(user)
user.serial_number ||= SecureRandom.uuid
end
end
class User < ApplicationRecord
end
class User < ApplicationController
def create
@user = CreateUser.call(user_params)
if @user
redirect_to root_path, notice: "User created!"
else
render :new, error: 'Failed to create user!'
end
end
def user_params
...
end
end
이 접근법은 우리에게 어떤 이점을 제공합니까?
Reference
이 문제에 관하여(서비스를 사용하여 콜백을 피하는 방법.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jetthoughts_61/how-to-avoid-callbacks-using-services-p7l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)