Sha256: f384f596000970de8f186841d2294bb63f01a6075705c7c6e54410038f57a60d

Contents?: true

Size: 1.39 KB

Versions: 11

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

11 entries across 11 versions & 2 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/to_json.rb
rubocop-0.93.1 lib/rubocop/cop/lint/to_json.rb
rubocop-0.93.0 lib/rubocop/cop/lint/to_json.rb
rubocop-0.92.0 lib/rubocop/cop/lint/to_json.rb
rubocop-0.91.1 lib/rubocop/cop/lint/to_json.rb
rubocop-0.91.0 lib/rubocop/cop/lint/to_json.rb