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
rubocop-1.22.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.21.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.20.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.19.1 lib/rubocop/cop/lint/to_json.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/rubocop-1.18.3/lib/rubocop/cop/lint/to_json.rb
rubocop-1.19.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.18.4 lib/rubocop/cop/lint/to_json.rb
rubocop-1.18.3 lib/rubocop/cop/lint/to_json.rb
rubocop-1.18.2 lib/rubocop/cop/lint/to_json.rb
rubocop-1.18.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.18.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.17.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.16.1 lib/rubocop/cop/lint/to_json.rb
rubocop-1.16.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.15.0 lib/rubocop/cop/lint/to_json.rb
cocRb-0.1.0 .bundle/ruby/3.0.0/gems/rubocop-1.14.0/lib/rubocop/cop/lint/to_json.rb
rubocop-1.14.0 lib/rubocop/cop/lint/to_json.rb
rubocop-1.13.0 lib/rubocop/cop/lint/to_json.rb