Sha256: 1ce3100923321a275e24ebd149061cdd957d7a46c5da6cece0f428288ad7e308

Contents?: true

Size: 1.38 KB

Versions: 38

Compression:

Stored size: 1.38 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

38 entries across 38 versions & 6 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/to_json.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/to_json.rb
rubocop-1.29.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.29.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.28.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.28.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.28.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.27.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.26.1 lib/rubocop/cop/lint/to_json.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/lint/to_json.rb
rubocop-1.26.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.25.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.25.0 lib/rubocop/cop/lint/to_json.rb
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/lint/to_json.rb
rubocop-1.24.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.24.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.23.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.22.3 lib/rubocop/cop/lint/to_json.rb
rubocop-1.22.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.22.1 lib/rubocop/cop/lint/to_json.rb