Sha256: f0202cb27eb57bd6a4a1e8778a600077220d2ce6fed17dc5ef8aecda8faaf0e7

Contents?: true

Size: 1.39 KB

Versions: 22

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop checks to make sure `#to_json` includes an optional argument.
      # When overriding `#to_json`, callers may invoke JSON
      # generation via `JSON.generate(your_obj)`.  Since `JSON#generate` allows
      # for an optional argument, your method should too.
      #
      # @example
      #   class Point
      #     attr_reader :x, :y
      #
      #     # bad, incorrect arity
      #     def to_json
      #       JSON.generate([x, y])
      #     end
      #
      #     # good, preserving args
      #     def to_json(*args)
      #       JSON.generate([x, y], *args)
      #     end
      #
      #     # good, discarding args
      #     def to_json(*_args)
      #       JSON.generate([x, y])
      #     end
      #   end
      #
      class ToJSON < Base
        extend AutoCorrector

        MSG = '`#to_json` requires an optional argument to be parsable ' \
          'via JSON.generate(obj).'

        def on_def(node)
          return unless node.method?(:to_json) && node.arguments.empty?

          add_offense(node) do |corrector|
            # The following used `*_args` because `to_json(*args)` has
            # an offense of `Lint/UnusedMethodArgument` cop if `*args`
            # is not used.
            corrector.insert_after(node.loc.name, '(*_args)')
          end
        end
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
rubocop-1.12.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.12.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.11.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.10.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.9.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.9.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.8.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.8.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.7.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.6.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.6.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.5.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.5.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.5.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.4.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.4.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.4.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.3.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.3.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.2.0 lib/rubocop/cop/lint/to_json.rb