Skip to content

Instantly share code, notes, and snippets.

@kzkn
Created March 18, 2021 15:11
Show Gist options
  • Save kzkn/44acb653ccf718a9f2a406e0e81f2831 to your computer and use it in GitHub Desktop.
Save kzkn/44acb653ccf718a9f2a406e0e81f2831 to your computer and use it in GitHub Desktop.
simple_form の association メソッドで collection を未指定な場合に警告する rubocop
module RuboCop
module Cop
module FooBar
class SimpleFormAssociationCollection < Base
MSG = 'Specify the `collection` option'.freeze
def_node_matcher :has_association_call?, <<~PATTERN
(block
(send _ :simple_form_for ...)
(args (arg _f))
`$(send (lvar _f) :association $...))
PATTERN
def_node_matcher :has_collection_option?, <<~PATTERN
(hash <(pair (sym :collection) _) ...>)
PATTERN
def on_block(node)
match = has_association_call?(node)
return if match.nil?
send_node, args_node = match
return if args_node.any? { |nd| has_collection_option?(nd) }
add_offense(send_node)
end
end
end
end
end
RSpec.describe RuboCop::Cop::FooBar::SimpleFormAssociationCollection, :config do
let(:config) { RuboCop::Config.new }
it 'bad' do
expect_offense(<<~RUBY)
simple_form_for user do |f|
f.association :group
^^^^^^^^^^^^^^^^^^^^ Specify the `collection` option
end
RUBY
end
it 'good' do
expect_no_offenses(<<~RUBY)
simple_form_for user do |f|
f.association :group, collection: current_company.groups
end
RUBY
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment