Skip to content

False positive for Style/FormatStringToken in Rails validates format #7436

@DMA57361

Description

@DMA57361

In one of our Rails apps we've a validation that uses the "format" helper to constrain a value to a matching regex, it seems the Style/FormatStringToken cop has incorrectly matched this a use of the format method, which it is not.


Expected behavior

Given an example.rb file with the following content:

class SomeModel < ApplicationRecord
  validates :colour, format: { with: /\A#[0-9a-fA-F]{6}\Z/, message: '%{colour} is not a valid hex colour' }
end

and running the command

rubocop example.rb --only Style/FormatStringToken

I expect to see no offenses.

Actual behavior

A single Style/FormatStringToken offense is reported

$ rubocop example.rb --only Style/FormatStringToken
Inspecting 1 file
C

Offenses:

example.rb:2:71: C: Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over template tokens (like %{foo}).
  validates :colour, format: { with: /\A#[0-9a-fA-F]{6}\Z/, message: '%{colour} is not a valid hex colour' }
                                                                      ^^^^^^^^^

1 file inspected, 1 offense detected

As an aside, the use of %<colour> in this context is not valid and would produce this error when attempting to save an invalid record:

I18n::MissingInterpolationArgument: missing interpolation argument :colour in "%<colour> is not a valid hex colour"

Steps to reproduce the problem

Covered above in expected behaviour

RuboCop version

$ rubocop -V
0.75.1 (using Parser 2.6.5.0, running on ruby 2.6.5 x86_64-darwin18)

Metadata

Metadata

Assignees

No one assigned

    Labels

    buglibrary specificThis issue is related to a particular library, like Rails or RSpec, and not Ruby itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions