Sha256: afcfce7b1e5ad4ace52231edb30d65b6817a96026d41791c2608402eb109b931

Contents?: true

Size: 1.08 KB

Versions: 4

Compression:

Stored size: 1.08 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
      #   # bad
      #   def to_json
      #   end
      #
      #   # good
      #   def to_json(*_args)
      #   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

4 entries across 4 versions & 2 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.90.0/lib/rubocop/cop/lint/to_json.rb
rubocop-0.90.0 lib/rubocop/cop/lint/to_json.rb
rubocop-0.89.1 lib/rubocop/cop/lint/to_json.rb
rubocop-0.89.0 lib/rubocop/cop/lint/to_json.rb