Class: RuboCop::Cop::Primer::PrimerOcticon
- Inherits:
-
Cop
- Object
- Cop
- RuboCop::Cop::Primer::PrimerOcticon
- Defined in:
- lib/rubocop/cop/primer/primer_octicon.rb
Overview
This cop ensures that components use System Arguments instead of CSS classes.
bad octicon(:icon) octicon(“icon”) octicon(“icon-with-daashes”) octicon(@ivar) octicon(condition > “icon” : “other-icon”)
good primer_octicon(:icon) primer_octicon(:“icon-with-daashes”) primer_octicon(@ivar) primer_octicon(condition > “icon” : “other-icon”)
Constant Summary collapse
- INVALID_MESSAGE =
<<~STR Replace the octicon helper with primer_octicon. See https://primer.style/view-components/components/octicon for details. STR
- SIZE_ATTRIBUTES =
%w[height width size].freeze
- STRING_ATTRIBUTES =
%w[aria- data-].freeze
- REST_ATTRIBUTES =
%w[title].freeze
- VALID_ATTRIBUTES =
[*SIZE_ATTRIBUTES, *STRING_ATTRIBUTES, *REST_ATTRIBUTES, "class"].freeze
- STRING_ATTRIBUTE_REGEX =
Regexp.union(STRING_ATTRIBUTES).freeze
- ATTRIBUTE_REGEX =
Regexp.union(VALID_ATTRIBUTES).freeze
- INVALID_ATTRIBUTE =
-1
Instance Method Summary collapse
Instance Method Details
#autocorrect(node) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/rubocop/cop/primer/primer_octicon.rb', line 71 def autocorrect(node) lambda do |corrector| kwargs = kwargs(node) # Converting arguments for the component classes = classes(kwargs) size_attributes = transform_sizes(kwargs) rest_attributes = rest_args(kwargs) args = arguments_as_string(node, size_attributes, rest_attributes, classes) if node.dot? corrector.replace(node.loc.expression, "#{node.receiver.source}.primer_octicon(#{args})") else corrector.replace(node.loc.expression, "primer_octicon(#{args})") end end end |
#on_send(node) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/rubocop/cop/primer/primer_octicon.rb', line 39 def on_send(node) return unless node.method_name == :octicon return unless node.arguments? kwargs = kwargs(node) return unless kwargs.type == :hash attributes = kwargs.keys.map(&:value) # Don't convert unknown attributes return unless attributes.all? { |attribute| attribute.match?(ATTRIBUTE_REGEX) } # Can't convert size return if octicon_size_attributes(kwargs) == INVALID_ATTRIBUTE # find class pair classes = classes(kwargs) return if classes == INVALID_ATTRIBUTE # check if classes are convertible if classes.present? system_arguments = ::Primer::Classify::Utilities.classes_to_hash(classes) invalid_classes = (system_arguments[:classes]&.split(" ") || []).select { |class_name| ::Primer::Classify::Validation.invalid?(class_name) } # Uses system argument that can't be converted return if invalid_classes.present? end add_offense(node, message: INVALID_MESSAGE) end |