Skip to content

Performance/ConstantRegexp with a constant defined in a subclass #205

@dvandersluis

Description

@dvandersluis

When a regexp depends on a constant defined in a subclass, neither of the fixes suggested by Performance/ConstantRegexp work:

class C
  def self.regexp
    %r{foo #{self::BASE_PATTERN}}
  end
end

class X < C
  BASE_PATTERN = /bar/
end

class Y < C
  BASE_PATTERN = /baz/
end

If the pattern is change to use the /o modifier, the first time the method is triggered the regexp will be interpolated for both subclasses:

X.regexp
=> /foo (?-mix:bar)/
Y.regexp
=> /foo (?-mix:bar)/

If the regexp is extracted to a constant, it needs to be duplicated in every subclass (and the regexp could be considerably more complicated than the example here).

RuboCop version

Include the output of rubocop -V or bundle exec rubocop -V if using Bundler. Here's an example:

$ [bundle exec] rubocop -V
rubocop -V
1.8.1 (using Parser 3.0.0.0, rubocop-ast 1.4.0, running on ruby 2.6.6 x86_64-darwin18)
  - rubocop-performance 1.9.2
  - rubocop-rails 2.9.1
  - rubocop-rspec 2.1.0

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