Skip to content

Commit b7c0eb8

Browse files
johnnyshieldsp
authored andcommitted
MONGOID-5168 Replace field[0] == ?$ with field.start_with?('$') -- easier to read and 30%+ faster (#5052)
Co-authored-by: shields <[email protected]>
1 parent 8c89366 commit b7c0eb8

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

lib/mongoid/criteria/queryable/selectable.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ def not(*criteria)
597597
end
598598
_mongoid_expand_keys(new_s).each do |k, v|
599599
k = k.to_s
600-
if c.selector[k] || k[0] == ?$
600+
if c.selector[k] || k.start_with?('$')
601601
c = c.send(:__multi__, [{'$nor' => [{k => v}]}], '$and')
602602
else
603603
if v.is_a?(Hash)
@@ -890,7 +890,7 @@ def expr_query(criterion)
890890
clone.tap do |query|
891891
normalized.each do |field, value|
892892
field_s = field.to_s
893-
if field_s[0] == ?$
893+
if field_s.start_with?('$')
894894
# Query expression-level operator, like $and or $where
895895
query.add_operator_expression(field_s, value)
896896
else

lib/mongoid/criteria/queryable/storable.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def add_field_expression(field, value)
3838
raise ArgumentError, "Field must be a string: #{field}"
3939
end
4040

41-
if field[0] == ?$
41+
if field.start_with?('$')
4242
raise ArgumentError, "Field cannot be an operator (i.e. begin with $): #{field}"
4343
end
4444

@@ -48,7 +48,7 @@ def add_field_expression(field, value)
4848
if value.is_a?(Hash) && selector[field].is_a?(Hash) &&
4949
value.keys.all? { |key|
5050
key_s = key.to_s
51-
key_s[0] == ?$ && !selector[field].key?(key_s)
51+
key_s.start_with?('$') && !selector[field].key?(key_s)
5252
}
5353
then
5454
# Multiple operators can be combined on the same field by
@@ -185,7 +185,7 @@ def add_operator_expression(operator, op_expr)
185185
raise ArgumentError, "Operator must be a string: #{operator}"
186186
end
187187

188-
unless operator[0] == ?$
188+
unless operator.start_with?('$')
189189
raise ArgumentError, "Operator must begin with $: #{operator}"
190190
end
191191

@@ -220,7 +220,7 @@ def add_one_expression(field, value)
220220
raise ArgumentError, "Field must be a string: #{field}"
221221
end
222222

223-
if field[0] == ?$
223+
if field.start_with?('$')
224224
add_operator_expression(field, value)
225225
else
226226
add_field_expression(field, value)

0 commit comments

Comments
 (0)