gpt4 book ai didi

ruby-on-rails - 处理两个相似对象的最佳实践

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

假设我有两个基本相同的不同 Controller / View 集。

营业时间和工作人员时间

第一个包含 business_id,后者包含 staff_id。否则它们看起来是一样的。 id、mon_start_time、mon_stop_time、tues_start_time、tues_stop_time 等...

1)由于它们非常相似,有没有办法对它们使用相同的 Controller ?这似乎没有多大意义,但我一直在思考它们有多相似以及有多少重复代码。

2)此外,对于每个人,我都有一个部分表格。我试图在工作时间和工作时间使用同一个。部分,在最简化的状态下看起来像:

-form_for(obj) do |f|
=f.error_messages %p =select obj.class, :mon_start_time, hours to =select obj.class, :mon_stop_time, hours

=link_to 'Back', obj_path

所以我需要传递 3 个独特的东西。'obj',business_hours 或 staff_hours。这在 form_for 中没问题,但我如何获得选择的第一个参数的小写 Controller 名称?我需要来自“obj”的“business_hour”和“staff_hour”。然后我需要它知道正确的“后退”链接。

我知道我可以将参数传递到部分,但我只是好奇是否有更巧妙的方法来处理这个问题。谢谢!

最佳答案

重复代码有持有成本,即维护成本。有时我们不知道这个成本有多高,直到我们重构重复代码并发现自己松了一口气:现在我可以只在一个地方更改业务规则。现在我可以停止输入两次了。

您可以使用两个 Controller ,但仍然重构重复的代码。一种方法是将公共(public)代码放在两个 Controller 都包含的模块中。

module CommonStuff

def stuff_that_is_the_same
end

end

controller FooController < ApplicationController

include CommonStuff

def stuff_that_is_different
# Stuff specific to Foo
stuff_that_is_the_same
# More stuff specific to Foo
end

end

controller BarController < ApplicationController

include CommonStuff

def stuff_that_is_different
# Stuff specific to Bar
stuff_that_is_the_same
# More stuff specific to Bar
end

end

关于ruby-on-rails - 处理两个相似对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2215583/

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