class RuboCop::Cop::Performance::Count
Model.where(id: [1, 2, 3]).to_a.count { |m| m.method == true }
becomes:
Model.where(id: [1, 2, 3].select { |m| m.method == true }.size
Example:
make ‘count` work with a block is to call `to_a.count {…}`.
array and then run the block on the array. A simple work around to
Other methods, such as `select`, will convert the association to an
`ActiveRecord` will ignore the block that is passed to `count`.
`ActiveRecord` compatibility:
Model.select(:value).count
Model.select(’field AS field_one’).count
[1, 2, 3].count { |e| e < 2 && e.even? }
[1, 2, 3].count { |e| e > 2 && e.odd? }
[1, 2, 3].count { |e| e < 2 }
[1, 2, 3].count { |e| e > 2 }
# good
array.select(&:value).count
[1, 2, 3].reject { |e| e > 2 }.count { |e| e.even? }
[1, 2, 3].select { |e| e > 2 }.count { |e| e.odd? }
[1, 2, 3].reject { |e| e > 2 }.length
[1, 2, 3].select { |e| e > 2 }.length
[1, 2, 3].reject { |e| e > 2 }.size
[1, 2, 3].select { |e| e > 2 }.size
# bad
@example
passed to the ‘count` call.
follow calls to `select` or `reject`. Querying logic can instead be
This cop is used to identify usages of `count` on an `Enumerable` that
def autocorrect(node)
def autocorrect(node) selector_node, selector, _counter = count_candidate?(node) selector_loc = selector_node.loc.selector return if selector == :reject range = source_starting_at(node) { |n| n.loc.dot.begin_pos } lambda do |corrector| corrector.remove(range) corrector.replace(selector_loc, 'count') end end
def eligible_node?(node)
def eligible_node?(node) !(node.parent && node.parent.block_type?) end
def on_send(node)
def on_send(node) return if rails_safe_mode? count_candidate?(node) do |selector_node, selector, counter| return unless eligible_node?(node) range = source_starting_at(node) do selector_node.loc.selector.begin_pos end add_offense(node, location: range, message: format(MSG, selector: selector, counter: counter)) end end
def source_starting_at(node)
def source_starting_at(node) begin_pos = if block_given? yield node else node.source_range.begin_pos end range_between(begin_pos, node.source_range.end_pos) end