Sha256: 74c7e7d3c480f497425cf1fc040237033237d9f53ffa5240d3ad8f11bac0c9c2

Contents?: true

Size: 1.62 KB

Versions: 13

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop is used to identify usages of `where.first` and
      # change them to use `find_by` instead.
      #
      # @example
      #   # bad
      #   User.where(name: 'Bruce').first
      #   User.where(name: 'Bruce').take
      #
      #   # good
      #   User.find_by(name: 'Bruce')
      class FindBy < Cop
        MSG = 'Use `find_by` instead of `where.%s`.'.freeze
        TARGET_SELECTORS = [:first, :take].freeze

        def_node_matcher :where_first, <<-PATTERN
          (send $(send _ :where ...) ${:first :take})
        PATTERN

        def on_send(node)
          return unless (recv_and_method = where_first(node))
          receiver, second_method = *recv_and_method

          range = range_between(receiver.loc.selector.begin_pos,
                                node.loc.selector.end_pos)

          add_offense(node, range, format(MSG, second_method))
        end

        def autocorrect(node)
          receiver, second_method = where_first(node)
          # Don't autocorrect where(...).first, because it can return different
          # results from find_by. (They order records differently, so the
          # 'first' record can be different.)
          return if second_method == :first

          where_loc = receiver.loc.selector
          first_loc = range_between(node.loc.dot.begin_pos,
                                    node.loc.selector.end_pos)

          lambda do |corrector|
            corrector.replace(where_loc, 'find_by')
            corrector.replace(first_loc, '')
          end
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/find_by.rb
rubocop-0.47.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.47.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.46.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.45.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.44.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.44.0 lib/rubocop/cop/rails/find_by.rb