Skip to content

Escape Regexps in search query by default #134

Open
@flvrone

Description

@flvrone

Guys, don't you think it's better to have query string "regexp-escaped" by-default in your example initializer from README?

This is what you have there now:

  ## Match partial words on both sides (slower)
  config.regex = Proc.new { |query| /#{query}/ }

  ## Match partial words on the beginning or in the end (slightly faster)
  # config.regex = Proc.new { |query| /^#{query}/ }
  # config.regex = Proc.new { |query| /#{query}$/ }

And I could have just query like this: ...., and it will match anything that has at least 4 characters. Well this is quite simple example, but I believe it could lead to a lot of unwanted (and not obvious) results.

I believe it's better to replace what you currently have with this:

  ## Match partial words on both sides (slower)
  config.regex = Proc.new { |query| /#{::Regexp.escape(query)}/ }

  ## Match partial words on the beginning or in the end (slightly faster)
  # config.regex = Proc.new { |query| /^#{::Regexp.escape(query)}/ }
  # config.regex = Proc.new { |query| /#{::Regexp.escape(query)}$/ }

UPDATE
It does not change anything actually, for some reason. Quite strange, it works in regular scopes though.


UPDATE 2
OK, I see that you're actually already escaping keywords here:

escaped_kw = Regexp.escape(kw)

but it actually has no effect for me on mongoid 6.4.2. So I believe it's a bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions