Skip to content

Commit

Permalink
Fix false negative against typical string formatting examples
Browse files Browse the repository at this point in the history
  • Loading branch information
kakutani committed Dec 19, 2014
1 parent 485531a commit 259ea9d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/rubocop/cop/style/format_string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ def offending_node?(node)
end

def format_method?(name, node)
receiver, method_name, args = *node
receiver, method_name, *args = *node

# commands have no explicit receiver
return false unless !receiver && method_name == name

# we do an argument count check to reduce false positives
args && args.children.size >= 2
args.size >= 2
end

def format?(node)
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/style/format_string_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@
expect(cop.messages)
.to eq(['Favor `sprintf` over `format`.'])
end

it 'registers an offense for format with 2 arguments' do
inspect_source(cop,
['format("%X", 123)'])
expect(cop.offenses.size).to eq(1)
expect(cop.messages)
.to eq(['Favor `sprintf` over `format`.'])
end
end

context 'when enforced style is format' do
Expand Down Expand Up @@ -106,6 +114,15 @@
expect(cop.messages)
.to eq(['Favor `format` over `sprintf`.'])
end

it 'registers an offense for sprintf with 2 arguments' do
inspect_source(cop,
["sprintf('%020d', 123)"])
expect(cop.offenses.size).to eq(1)
expect(cop.messages)
.to eq(['Favor `format` over `sprintf`.'])
end

end

context 'when enforced style is percent' do
Expand All @@ -127,6 +144,15 @@
.to eq(['Favor `String#%` over `sprintf`.'])
end

it 'registers an offense for sprintf with 3 arguments' do
inspect_source(cop,
['format("%d %04x", 123, 123)'])
expect(cop.offenses.size).to eq(1)
expect(cop.messages)
.to eq(['Favor `String#%` over `format`.'])
end


it 'accepts format with 1 argument' do
inspect_source(cop,
['format :xml'])
Expand Down

0 comments on commit 259ea9d

Please sign in to comment.