Sha256: eae7eb986ac415b2238c0f4a54f9f17c14117ed7b311024d614f9a3a1ff4bdaf

Contents?: true

Size: 1.57 KB

Versions: 9

Compression:

Stored size: 1.57 KB

Contents

# encoding: utf-8

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`.'
        TARGET_SELECTORS = [:first, :take]

        def on_send(node)
          receiver, second_method, _selector = *node
          return unless TARGET_SELECTORS.include?(second_method)
          return if receiver.nil?
          _scope, first_method = *receiver
          return unless first_method == :where
          begin_of_offense = receiver.loc.selector.begin_pos
          end_of_offense = node.loc.selector.end_pos
          range = Parser::Source::Range.new(node.loc.expression.source_buffer,
                                            begin_of_offense,
                                            end_of_offense)

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

        def autocorrect(node)
          receiver, = *node
          where_loc = receiver.loc.selector
          first_loc = Parser::Source::Range.new(
            node.loc.expression.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

9 entries across 9 versions & 1 rubygems

Version Path
rubocop-0.35.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.35.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.34.2 lib/rubocop/cop/rails/find_by.rb
rubocop-0.34.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.34.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.33.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.32.1 lib/rubocop/cop/rails/find_by.rb
rubocop-0.32.0 lib/rubocop/cop/rails/find_by.rb
rubocop-0.31.0 lib/rubocop/cop/rails/find_by.rb