【问题标题】:Possible to DRY up the same method in two different controllers?可以在两个不同的控制器中干燥相同的方法吗?
【发布时间】:2016-03-16 18:03:09
【问题描述】:

我有一个 Rails 项目,它有一个 api 部分和一个常规部分。他们有一些常用的方法,例如,我有两个这样的控制器:

class PlacementController < ApplicationSafeController

  def zip
    file = ZipService::ZipGenerator.create_zip
    send_data(file.read, type: 'application/zip')
    File.delete(file.path)
  end
end  

class Api::ZipsController < ApiController

  def single_zip
    file = ZipService::ZipGenerator.create_zip
    send_data(file.read, type: 'application/zip')
    File.delete(file.path)   
  end 
end

我的ApiControllerApplicationSafeController 都继承自ApplicationController。我的问题是,在不使根 ApplicationController 变脏的情况下清理它的最佳方法是什么? (通过在那里添加一个新方法)。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby api dry


    【解决方案1】:

    您是共享代码的模块/关注点。将可共享代码包含在模块中,然后将该模块包含在所需的控制器中。这是 Ruby 做这件事的方式。

    module Zippable
      def zip
        file = ZipService::ZipGenerator.create_zip
        send_data(file.read, type: 'application/zip')
        File.delete(file.path)
      end
    end  
    
    class PlacementController < ApplicationSafeController
    
      include Zippable
    
      #Example Usage
      def show
        zip
      end
    end  
    
    class Api::ZipsController < ApiController
    
      include Zippable
    end
    

    【讨论】:

    • 我想我的问题是 send_data 来自 ApplicationController。我试图做类似的事情,只有 yield 而不是 send_data 然后通过一个块传递 send_data 但它似乎有点疯狂
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多