Skip to content

Commit

Permalink
Register an offence for date strings without a timezone (rubocop#3951)
Browse files Browse the repository at this point in the history
  • Loading branch information
sinsoku authored and bbatsov committed Jan 24, 2017
1 parent 5d0251b commit 406b4ef
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

* [#3915](https://github.com/bbatsov/rubocop/issues/3915): Make configurable whitelist for `Lint/SafeNavigationChain` cop. ([@pocke][])
* [#3944](https://github.com/bbatsov/rubocop/issues/3944): Allow keyword arguments in `Style/RaiseArgs` cop. ([@mikegee][])
* [#3951](https://github.com/bbatsov/rubocop/pull/3951): Make `Rails/Date` cop to register an offence for a string without timezone. ([@sinsoku][])

### New features

Expand Down Expand Up @@ -2617,3 +2618,4 @@
[@zverok]: https://github.com/zverok
[@backus]: https://github.com/backus
[@pat]: https://github.com/pat
[@sinsoku]: https://github.com/sinsoku
14 changes: 12 additions & 2 deletions lib/rubocop/cop/rails/date.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ def on_const(node)
end

def on_send(node)
receiver, method_name, *args = *node
receiver, method_name = *node
return unless receiver && bad_methods.include?(method_name)

chain = extract_method_chain(node)
return if safe_chain?(chain)

return if method_name == :to_time && args.length == 1
return if method_name == :to_time && safe_to_time?(node)

add_offense(node, :selector,
format(MSG_SEND,
Expand Down Expand Up @@ -109,6 +109,16 @@ def safe_chain?(chain)
(chain & bad_methods).empty? || !(chain & good_methods).empty?
end

def safe_to_time?(node)
receiver, _method_name, *args = *node
if receiver.str_type?
zone_regexp = /[+-][\d:]+\z/
receiver.str_content.match(zone_regexp)
else
args.length == 1
end
end

def good_days
style == :strict ? [] : [:current, :yesterday, :tomorrow]
end
Expand Down
14 changes: 14 additions & 0 deletions spec/rubocop/cop/rails/date_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@
end
end

context 'when a string literal with timezone' do
it 'does not register an offense' do
inspect_source(cop, '"2016-07-12 14:36:31 +0100".to_time(:utc)')
expect(cop.offenses).to be_empty
end
end

context 'when a string literal without timezone' do
it 'registers an offense' do
inspect_source(cop, '"2016-07-12 14:36:31".to_time(:utc)')
expect(cop.offenses.size).to eq(1)
end
end

it 'does not blow up in the presence of a single constant to inspect' do
inspect_source(cop, 'A')
expect(cop.offenses).to be_empty
Expand Down

0 comments on commit 406b4ef

Please sign in to comment.