【问题标题】:How can I decorate STI models with modularized decorators using Draper?如何使用 Draper 使用模块化装饰器装饰 STI 模型?
【发布时间】:2014-06-16 19:14:11
【问题描述】:

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

我想将一些与控制台相关的、人类可读的功能引入新的装饰器中。

我的第一个想法是将它们放在一个模块中,例如 Human::XxxDecorator,使它们与我的普通视图层装饰器隔离:它们仅用于 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 装饰器推理代码之前(我只是假设这是最好的起点),这是一个已经解决的问题并且我遗漏了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby draper


    【解决方案1】:

    正如我在 cmets 中所写,移除车辆的内置装饰,并为您的车辆编码:

    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
    

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

    【讨论】:

    • 不过,我试图避免由此暗示的手动工作;我知道我可以手工完成所有工作。
    • 祝你好运,不过我怀疑有什么简单明了的东西
    • 是的,我怀疑你在进一步研究代码后是对的 :( 但这太糟糕了,因为上下文相关的装饰器会很酷。
    • 嗯,是的,不是的,它们会有点神奇,在这种情况下我对纯代码很满意
    • 我可以在探索代码中使用魔法,尽管我也有其他用途。但是嗯——只是希望它不需要任何努力。
    【解决方案2】:

    你可以使用常量化:

    def dfleet
      dfleet_decorator_class.new(object.dfleet)
    end
    
    def dfleet_decorator_class
      "#{object.dfleet.class}Decorator".constantize
    end
    

    【讨论】:

      【解决方案3】:

      使用装饰:.这是一个例子:CLICK

      【讨论】:

      • 请参阅我在 OP 中关于 decorates 的评论。
      猜你喜欢
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多