Search code examples
ruby-on-railsoptimizationdry

How can I Remove CodeClimate similar code from strong params?


I'm analyzing my code in CodeClimate.com and I have a similar code problem always in the same lines:

params.permit(some parameters here)

CodeClimate is detecting this code as similar based only in the mass of the code, not in the content, so my quality is not improving due to this.

Is there a way to tell CodeClimate that this code is not repeated or even similar, as long as it's a parameters hash?


Solution

  • Why not to refactor such issues? Say, you have code:

    class PostsController < ApplicationController
      # ...
    
      def resource_params
        params.require(:post).permit(:title, :body)
      end
    end
    
    class CommentsController < ApplicationController
      # ...
    
      def resource_params
        params.require(:comment).permit(:name, :email, :body)
      end
    end
    

    You can move repeating code into superclass, leaving in subclasses only differences:

    class ApplicationController < ActionControllerBase
      # ...
    
      def resource_params
        params.require(resource_name).permit(*permitted_resource_params)
      end
    end
    
    class PostsController < ApplicationController
      # ...
    
      def resource_name
        :post
      end
    
      def permitted_resource_params
        [:title, :body]
      end
    end
    
    class CommentsController < ApplicationController
      # ...
    
      def resource_name
        :comment
      end
    
      def permitted_resource_params
        [:name, :email, :body]
      end
    end
    

    And, of course, if in some controller you have different rules of params permission — you could redefine resource_params method in it.