Class: Hone::Patterns::BlockToProc
- Defined in:
- lib/hone/patterns/block_to_proc.rb
Overview
Pattern: array.map { |x| x.to_s } -> array.map(&:to_s)
When a block simply calls a single method on its parameter with no arguments, the Symbol#to_proc shorthand is more idiomatic and slightly more efficient.
Examples:
# Bad: verbose block
array.map { |x| x.to_s }
array.select { |item| item.valid? }
# Good: Symbol#to_proc shorthand
array.map(&:to_s)
array.select(&:valid?)
Constant Summary collapse
- APPLICABLE_METHODS =
Methods that commonly take blocks and can use Symbol#to_proc
%i[ map collect select find_all reject detect find any? all? none? one? sort_by group_by partition max_by min_by minmax_by count take_while drop_while filter filter_map ].freeze
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods inherited from Base
#add_finding, inherited, #initialize, scan_file
Constructor Details
This class inherits a constructor from Hone::Patterns::Base
Instance Method Details
#visit_call_node(node) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/hone/patterns/block_to_proc.rb', line 30 def visit_call_node(node) super return unless APPLICABLE_METHODS.include?(node.name) return unless node.block.is_a?(Prism::BlockNode) block = node.block return unless single_param_block?(block) return unless block_body_is_single_method_call?(block) param_name = extract_single_param_name(block) method_name = extract_called_method_name(block) return unless param_name && method_name add_finding( node, message: "Use `.#{node.name}(&:#{method_name})` instead of `.#{node.name} { |#{param_name}| #{param_name}.#{method_name} }` for Symbol#to_proc shorthand", speedup: "Minor, but more idiomatic Ruby" ) end |