Skip to content

Prevent feature flag in ActiveRecord scope

Albert requested to merge alberts-rubocop-no-feature-flag-in-scope into master

What does this MR do and why?

Adds a cop to stop the use of feature flag in an ActiveRecord scope.

Having a feature flag in a scope makes the scope behaviour uncertain. Given that a scope can be used in many places, such as through a class method Project.scope, or an instance method project.scope, a feature flag in a scope could lead to unexpected behaviour where the scope is used.

A preferred alternative is to define 2 separate scope implementations, each doing one thing. The caller of the scope can toggle between the 2 scopes using a feature flag.

    # bad:
    #   class Meal < ApplicationRecord
    #     scope: with_fruits, -> do
    #       if Feature.enabled?(:with_apples)
    #         include(:apples)
    #       else
    #         include(:oranges)
    #       end
    #     end
    #   end
    #
    # good:
    #   class Meal < ApplicationRecord
    #     scope: with_apples, -> { include(:apples) }
    #     scope: with_oranges, -> { include(:oranges) }
    #   end
    #
    #   if Feature.enabled?(:with_apples)
    #     Meal.with_apples
    #   else
    #     Meal.with_oranges
    #   end

Screenshots or screen recordings

Screenshots are required for UI changes, and strongly recommended for all other merge requests.

How to set up and validate locally

Numbered steps to set up and validate the change are strongly suggested.

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Albert

Merge request reports