Sha256: 2fe213502b7eaff8749f8acc5e636d5837162c82a08227c8ca107fa70aa05471

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # This cop checks the args passed to `fail` and `raise`.
      class RaiseArgs < Cop
        def on_send(node)
          return unless command?(:raise, node) || command?(:fail, node)

          case style
          when :compact
            check_compact(node)
          when :exploded
            check_exploded(node)
          end
        end

        private

        def check_compact(node)
          _receiver, selector, *args = *node

          return unless args.size > 1

          convention(node, :expression, message(selector))
        end

        def check_exploded(node)
          _receiver, selector, *args = *node

          return unless args.size == 1

          arg, = *args

          if arg.type == :send && arg.loc.selector.is?('new')
            _receiver, _selector, *constructor_args = *arg

            # Allow code like `raise Ex.new(arg1, arg2)`.
            unless constructor_args.size > 1
              convention(node, :expression, message(selector))
            end
          end
        end

        def style
          case cop_config['EnforcedStyle']
          when 'compact' then :compact
          when 'exploded' then :exploded
          else fail 'Unknown style selected!'
          end
        end

        def message(method)
          case style
          when :compact
            "Provide an exception object as an argument to #{method}."
          when :exploded
            "Provide an exception class and message as arguments to #{method}."
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubocop-0.15.0 lib/rubocop/cop/style/raise_args.rb
rubocop-0.14.1 lib/rubocop/cop/style/raise_args.rb