Sha256: e6027349751a6834beeaf607a5515189485ce9d851f4a51f99c6763fdb28b209

Contents?: true

Size: 1.57 KB

Versions: 6

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

require "rubocop"
require "ariadne/classify/utilities"

# :nocov:
module RuboCop
  module Cop
    module Ariadne
      # This cop ensures that components use System Arguments instead of CSS classes.
      #
      # bad
      # Component.new(classes: "mr-1")
      #
      # good
      # Component.new(mr: 1)
      class SystemArgumentInsteadOfClass < BaseCop
        INVALID_MESSAGE = <<~STR
          Avoid using CSS classes when you can use System Arguments: https://ariadne.style/view-components/system-arguments.
        STR

        def on_send(node)
          return unless valid_node?(node)
          return unless node.arguments?

          # we are looking for hash arguments and they are always last
          kwargs = node.arguments.last

          return unless kwargs.type == :hash

          # find classes pair
          classes_arg = kwargs.pairs.find { |kwarg| kwarg.key.value == :classes }

          return if classes_arg.nil?
          return unless classes_arg.value.type == :str

          # get actual classes
          classes = classes_arg.value.value

          attributes = ::Ariadne::Classify::Utilities.classes_to_hash(classes)

          # no classes are fixable
          return if attributes[:classes] == classes

          add_offense(classes_arg, message: INVALID_MESSAGE)
        end

        def autocorrect(node)
          lambda do |corrector|
            args = ::Ariadne::Classify::Utilities.classes_to_args(node.value.value)
            corrector.replace(node.loc.expression, args)
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ariadne_view_components-0.0.6 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb
ariadne_view_components-0.0.5 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb
ariadne_view_components-0.0.4 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb
ariadne_view_components-0.0.3 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb
ariadne_view_components-0.0.2 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb
ariadne_view_components-0.0.1 lib/rubocop/cop/ariadne/system_argument_instead_of_class.rb