Sha256: ba6ed458b757b7804ac279620a2a35d3b93b92150e9f5cf395752b3d025bb025

Contents?: true

Size: 1.37 KB

Versions: 191

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

191 entries across 184 versions & 18 rubygems

Version Path
rubocop-1.70.0 lib/rubocop/cop/lint/to_json.rb
minato_ruby_api_client-0.2.2 vendor/bundle/ruby/3.2.0/gems/rubocop-1.64.1/lib/rubocop/cop/lint/to_json.rb
rubocop-1.69.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.69.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.69.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.68.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.67.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.66.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.66.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.65.1 lib/rubocop/cop/lint/to_json.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/rubocop-1.64.1/lib/rubocop/cop/lint/to_json.rb
rubocop-1.65.0 lib/rubocop/cop/lint/to_json.rb
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/lint/to_json.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/lint/to_json.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/lint/to_json.rb
katalyst-govuk-formbuilder-1.9.2 vendor/bundle/ruby/3.3.0/gems/rubocop-1.64.1/lib/rubocop/cop/lint/to_json.rb
rubocop-1.64.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.63.4 lib/rubocop/cop/lint/to_json.rb
rubocop-1.63.3 lib/rubocop/cop/lint/to_json.rb
rubocop-1.63.2 lib/rubocop/cop/lint/to_json.rb