Reputation: 812
I'm have a Rails project which has an api part and the regular one. They have some common methods, for example, I have two controllers like so:
class PlacementController < ApplicationSafeController
def zip
file = ZipService::ZipGenerator.create_zip
send_data(file.read, type: 'application/zip')
File.delete(file.path)
end
end
and
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
And both my ApiController
and ApplicationSafeController
inherit from ApplicationController
. My question is, what is the best way to clean this up without making the root ApplicationController
dirty? (by adding a new method there). Thanks!
Upvotes: 0
Views: 106
Reputation: 3984
You a module/concern to share code. Enclose shareable code in a module, then include that module in the required controllers. It's the Ruby way of doing this thing.
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
Upvotes: 1