Gem的适配器模式使用多个组合类?

时间:2015-09-11 14:48:23

标签: ruby

我正在使用Axlsx gem(https://github.com/randym/axlsx)来生成excel文件。我想重构我的代码,以便我有一个围绕宝石的包装,以防我想要切换宝石。

通过这个让我想起了适配器设计模式。但是,在主Package对象下面嵌套了很多对象,我对如何为它实际创建适配器感到困惑。例如:

  1. 您创建了一个Package对象
  2. 您可以访问此Workbook对象
  3. 中的Package
  4. 您可以从Sheet对象访问Workbook,反之亦然
  5. 以下是我的一些课程:

    class ReportGenerator::Base
      ...
      def create_workbook
        ...
        @package   = Axlsx::Package.new <---------------------------
        @workbook  = @package.workbook <---------------------------
        @workbook.use_shared_strings = true
      end
    
    
    class Sheet::Base
      def initialize(workbook, question, options = {})
        ...
        @sheet = workbook.add_worksheet(:name => sheet_name) <---------------------------
      end
    
      def styles
        @styles ||= {
          "title"                 => @sheet.workbook.styles.add_style(:sz => 20, :b => true, :alignment => { :wrap_text => true }),
          "bold"                  => @sheet.workbook.styles.add_style(:b => true),
          "header"                => @sheet.workbook.styles.add_style(:fg_color => "FFFFFF", :bg_color => "ff3333", :sz => 12, :b => true, :alignment => {:horizontal => :center}, :border => {:style => :thin, :color => "FFFFFF"}),
          "subheader"             => @sheet.workbook.styles.add_style(:fg_color  => "FFFFFF", :bg_color => "ff3333", :sz => 12, :b => true, :alignment => {:horizontal => :center}),
          "subheader_border_left" => @sheet.workbook.styles.add_style(:fg_color  => "FFFFFF", :bg_color => "ff3333", :sz => 12, :b => true, :alignment => {:horizontal => :center}, :border => {:style => :thin, :color => "FFFFFF", :edges => [:left]}),
          "blue_link"             => @sheet.workbook.styles.add_style(:fg_color => '0000FF'),
          "wrap_text"             => @sheet.workbook.styles.add_style(:alignment => { :wrap_text => true, :horizontal => :left }),
          "percentage"            => @sheet.workbook.styles.add_style(:format_code => "0.00%")
        }
      end
    

    这是我的第一次尝试:

    class ExcelWriter
      def initialize
        @package = Axlsx::Package.new
      end
    
      def workbook
        @package.workbook
      end
    
      # starting to feel like it's not doable within one class..?
    
    end
    

    涉及到如此多的课程,感觉我无法将所有内容都包装到一个适配器中?或者也许我做错了?任何提示都会受到欢迎。

1 个答案:

答案 0 :(得分:1)

专注于您实际使用的内容,而不是现有的Axlsx gem的基础设施。这样,您可以将多个Axlsx对象的工作组合成1个方法调用。

我不知道你实际使用的是什么,所以我很难说你需要哪些物品。