gpt4 book ai didi

ruby-on-rails - 如何使用 Draper 使用模块化装饰器装饰 STI 模型?

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

我将 Draper 用于一般的 View 层装饰器。

我有一些与控制台相关的、人类可读性强的功能,我想加入新的装饰器。

我的第一个想法是将它们放在一个模块中,例如 Human::XxxDecorator,使它们与我的普通 View 层装饰器隔离:它们仅用于 rails c 调试/黑客攻击/测试工作。

这在顶层工作得很好;我可以使用命名空间装饰器显式装饰模型。

现在我需要装饰一组 STI 车辆。我不确定在相同的装饰器模块中创建特定于车辆类型的装饰器的最佳方法是什么,例如,我有:

  • Human::CarDecorator
  • Human::TruckDecorator
  • Human::MotorcycleDecorator

我不确定如何获取,例如,

pry » dfleet = Human::FleetDecorator.new(Fleet.find(1))

到其嵌入的车辆集合,每个车辆都有来自 Human 模块的适当装饰器。使用 decorates 的幼稚方法行不通;我得到:

Draper::UninferrableDecoratorError: Could not infer a decorator for Vehicle

组合:

  • 来自特定模块的装饰器,以及
  • 适用于 STI 模型的装饰器

正在扔东西。

在深入研究 Draper 装饰器推理代码之前(我只是假设这是最好的起点),这个问题是否已经解决并且我遗漏了什么?

最佳答案

正如我在评论中所写,移除你车辆的内置装饰,然后编写你的代码:

def vehicles
object.vehicles.map do |v|
# logic to instantiate proper decorator
end
end

黑客传入:

module Human
class FleetDecorator < Draper::Decorator
decorates_association :vehicles, with: ::Human::VehicleDecoratorDispatcher
end

class VehicleDecoratorDispatcher < Draper::Decorator
def initialize(*args)
super
@object = ... # here you build the proper decorator based on the rules on @object
end

end
end

但我怀疑这是否更清楚...

关于ruby-on-rails - 如何使用 Draper 使用模块化装饰器装饰 STI 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24250567/

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