Sha256: 26e44255ef59f774e68c848680b5eca4600258f4a54b039a4a34512d95f28877

Contents?: true

Size: 1.79 KB

Versions: 13

Compression:

Stored size: 1.79 KB

Contents

# encoding: utf-8
# 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 = Parser::Source::Range.new(node.source_range.source_buffer,
                                            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 = Parser::Source::Range.new(
            node.source_range.source_buffer,
            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
fluent-plugin-detect-memb-exceptions-0.0.2 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/rails/find_by.rb
fluent-plugin-detect-memb-exceptions-0.0.1 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/rails/find_by.rb
rubocop-0.42.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.41.2 lib/rubocop/cop/rails/find_by.rb
rubocop-0.41.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.41.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.40.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.39.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.38.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.37.2 lib/rubocop/cop/rails/find_by.rb
rubocop-0.37.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.37.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.36.0 lib/rubocop/cop/rails/find_by.rb