Skip to content

Consider Rails.env checks to be an anti-pattern.Β #589

@ioquatix

Description

@ioquatix

We would like to prevent something if Rails.env.production? type of code leaking into our code base. Specifically, we'd prefer that it's configuration driven, as in:

# bad
if Rails.env.production?
  add_job
end

# good
if Config.add_jobs?
  add_job
end

So we see Rails.env.(environment)? as an anti-pattern.

We have been trying out some proof-of-concept:

module Cop
  class EnvironmentCheck < RuboCop::Cop::Cop
    def_node_matcher :environment_check, <<~PATTERN
      (send (send (const nil? :Rails) :env) $_)
    PATTERN

    def on_send(node)
      environment_check(node) do |method|
        add_offense(node, message: message(method))
      end
    end

    private

    def message(method)
      "Using conditional logic like Rails.env.#{method} is an anti-pattern. Please replace with configuration specific to an environment."
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions