可以在两个不同的控制器中干掉相同的方法吗?

时间:2016-03-16 18:03:09

标签: ruby-on-rails ruby api dry

我有一个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变脏的情况下清理它的最佳方法是什么? (通过添加新方法)。谢谢!

1 个答案:

答案 0 :(得分: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