gpt4 book ai didi

ruby-on-rails - 修复 ruby​​ 中的重复方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:56:54 25 4
gpt4 key购买 nike

我正在用 ruby​​ on rails 编写 API,我发现我的方法非常重复。这就是我几乎所有方法的样子。它们都遵循相似的结构;我只是捕获了我的一个方法并将它放在这里:

def create
if current_user

@object = Object.new(object_params)

if @object.save
render json: {
status: "SUCCESS",
message: "object saved"
}, status: :ok
else
render json: {
status: "ERROR",
message: "Could not save object"
}, status: :unprocessable_entity
end
else
render json: {
status: "UNAUTHORIZED"
}, status: :unauthorized
end
end

当然,并不是我的所有方法都创建和保存对象。但它们都遵循相似的模式。首先我检查 current_user 是否不为 nil。如果是,我将呈现一个 JSON 响应:

if current_user
# do something
else
render json: {
status: "UNAUTHORIZED"
}

如果找到当前用户,并且必须运行的任何方法都成功,那么我将呈现另一个 JSON 响应:

if everything_went_well
render json: {
status: "SUCCESS",
message: "Everything went ok!"
}
else
render json: {
status: "ERROR",
message: "There was a problem!"
}
end

我很确定有一种方法可以抽象出这种功能。我在网上查找了对项目的其他部分(即模型和 View )有帮助的提示。然而,我在网上看到的大多数提示都不太适合我 Controller 中的代码。

最佳答案

您可以使用 before_filter为了这。请注意,当 before_action 已经呈现一个 View 时,将不再调用操作本身。

before_action :check_permission

def create
@object = Object.new(object_params)

if @object.save
render json: {
status: "SUCCESS",
message: "object saved"
}, status: :ok
else
render json: {
status: "ERROR",
message: "Could not save object"
}, status: :unprocessable_entity
end
end

private

def check_permission
return if current_user

render json: {
status: "UNAUTHORIZED"
}, status: :unauthorized
end

关于ruby-on-rails - 修复 ruby​​ 中的重复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com