gpt4 book ai didi

ruby - 如何从此 Ruby 函数中删除重复项?

转载 作者:太空宇宙 更新时间:2023-11-03 18:19:51 24 4
gpt4 key购买 nike

谁能告诉我如何简化这个 Ruby 函数?

class Profile < ActiveRecord::Base

before_create :set_defaults

def set_defaults
self.users_sort_column = "created_at"
self.companies_sort_column = "name"
self.people_sort_column = "last_name"
self.projects_sort_column = "name"
self.invoices_sort_column = "number"
self.payments_sort_column = "number"

self.users_sort_direction = "desc"
self.companies_sort_direction = "asc"
self.people_sort_direction = "asc"
self.projects_sort_direction = "asc"
self.invoices_sort_direction = "desc"
self.payments_sort_direction = "desc"
end

end

里面重复的太多了。感谢您的帮助。

P.S:每个用户都应该能够更新他的个人资料,这就是我将所有这些值存储在数据库中而不是模型中的原因。

最佳答案

我觉得没有重复的代码可以这样写:

def set_defaults
sort_column_direction = {
users: ["created_at", "desc"],
companies: ["name", "asc"],
people: ["last_name", "asc"],
projects: ["name", "asc"],
invoices: ["number", "desc"],
payments: ["number", "desc"]
}
sort_column_direction.each do |key,value|
self.send("#{key}_sort_column=", value[0])
self.send("#{key}_sort_direction=", value[1])
end
end

关于ruby - 如何从此 Ruby 函数中删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20246548/

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