Sha256: ba6ed458b757b7804ac279620a2a35d3b93b92150e9f5cf395752b3d025bb025

Contents?: true

Size: 1.37 KB

Versions: 195

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # 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

195 entries across 188 versions & 19 rubygems

Version Path
rubocop-1.50.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.50.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.50.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.49.0 lib/rubocop/cop/lint/to_json.rb
call_your_name-0.1.0 vendor/bundle/ruby/3.1.0/gems/rubocop-1.48.1/lib/rubocop/cop/lint/to_json.rb
rubocop-1.48.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.48.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.47.0 lib/rubocop/cop/lint/to_json.rb
zilla-0.2.0 vendor/bundle/ruby/3.2.0/gems/rubocop-1.46.0/lib/rubocop/cop/lint/to_json.rb
rubocop-1.46.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.45.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.45.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.44.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.44.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.43.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.42.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.41.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.41.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.40.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.39.0 lib/rubocop/cop/lint/to_json.rb