HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Repetitive controller with all methods nearly identical

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nearlyallwithidenticalcontrollermethodsrepetitive

Problem

I have an API with the following code

class API::V1::ReceptionController  200
      end

      def cliente
        jid = ClienteFornecedorWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def nota_fiscal
        jid = NotaFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def venda
        jid = VendaWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def reducaoz
        jid = ReducaoZWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def impressora_fiscal
        jid = ImpressoraFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end
..............


and so on. What happens is: every method call a different worker, but all the body's methods are pretty much the same. My question is: how can I reduce this methods to maybe just one?

Solution

Some notes:

-
I don't know if there is an agreement on the community on that, but I would definitely use the de-facto language of the computer industry (translating the API routes if needed, of course).

-
I'd write parens on "normal" (non-DSL) method calls.

-
That's a lot of actions. Why don't you refactor it to have a unique action with a param?

I'd write:

class API::V1::ReceptionController  ProdutoWorker, ....}

  def process
    worker_class = WorkerClasses[params[:key].to_sym]
    if worker_class
      jid = worker_class.perform_async(params[:document])
      render(json: {jid: jid}, :status => 200)
    else
      render(json: {errors: "Unknown key: #{params[:key]}"}, :status => 400)
    end
  end


(and change the routes accordingly, of course)

Code Snippets

class API::V1::ReceptionController < API::V1::APIController
  before_filter :ensure_document_exists
  WorkerClasses = {:produto => ProdutoWorker, ....}

  def process
    worker_class = WorkerClasses[params[:key].to_sym]
    if worker_class
      jid = worker_class.perform_async(params[:document])
      render(json: {jid: jid}, :status => 200)
    else
      render(json: {errors: "Unknown key: #{params[:key]}"}, :status => 400)
    end
  end

Context

StackExchange Code Review Q#57788, answer score: 4

Revisions (0)

No revisions yet.