我有一个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
我的ApiController
和ApplicationSafeController
都来自ApplicationController
。我的问题是,在不使根ApplicationController
变脏的情况下清理它的最佳方法是什么? (通过添加新方法)。谢谢!
答案 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