Ingo
Ingo

Reputation: 812

Possible to DRY up the same method in two different controllers?

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

Answers (1)

Babar Al-Amin
Babar Al-Amin

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

Related Questions