代码之家  ›  专栏  ›  技术社区  ›  Jack M.

大哈希创建模式

  •  1
  • Jack M.  · 技术社区  · 6 年前

    我正在使用pdftk填充一个大的(155字段)PDF。我用PDF的字段名和要填充的值创建大量散列。

    PdfJob 将模型中的所有数据收集到哈希中,并将该哈希传递到 wrapper around pdftk 储存在 $PDFTK .

    class PdfJob
      def perform(model)
        $PDFTK.fill_form('path/to/fillable.pdf', Tempfile.new, Fields.call(model))
      end
    
      private
    
      class Fields
        def self.call(model)
          {
            OWNER_NAME: "#{model.first_name} #{model.last_name}",
            TOTAL_PRICE: calculate_total_price(model),
            FOO: 'bar',
            # 152 more lines of key/value pairs.
          }
        end
    
        def self.calculate_total_price(model)
          # Most of these methods are multi-line.
          model.item_relations.sum(&:price)
        end
    
        # about 50 more class methods to simplify assignment in #call()
      end
    end
    

    我正在寻找一种设计模式或其他方法来将这个散列分解成多个类、方法或其他一些单元,这样我就不会以 Fields 使用近250行几乎不稳定的键/值对和帮助器方法初始化。

    0 回复  |  直到 6 年前