Class: RuboCop::Cop::Rails::TimeZone
- Inherits:
-
RuboCop::Cop
- Object
- RuboCop::Cop
- RuboCop::Cop::Rails::TimeZone
- Includes:
- ConfigurableEnforcedStyle
- Defined in:
- lib/rubocop/cop/rails/time_zone.rb
Overview
This cop checks for the use of Time methods without zone.
Built on top of Ruby on Rails style guide (rails.rubystyle.guide#time) and the article danilenko.org/2012/7/6/rails_timezones/
Two styles are supported for this cop. When EnforcedStyle is ‘strict’ then only use of Time.zone is allowed.
When EnforcedStyle is ‘flexible’ then it’s also allowed to use Time.in_time_zone.
Constant Summary collapse
- MSG =
'Do not use `%<current>s` without zone. Use `%<prefer>s` ' \ 'instead.'
- MSG_ACCEPTABLE =
'Do not use `%<current>s` without zone. ' \ 'Use one of %<prefer>s instead.'
- MSG_LOCALTIME =
'Do not use `Time.localtime` without ' \ 'offset or zone.'
- GOOD_METHODS =
%i[zone zone_default find_zone find_zone!].freeze
- DANGEROUS_METHODS =
%i[now local new parse at current].freeze
- ACCEPTED_METHODS =
%i[in_time_zone utc getlocal xmlschema iso8601 jisx0301 rfc3339 httpdate to_i to_f].freeze
Instance Method Summary collapse
Instance Method Details
#autocorrect(node) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/rubocop/cop/rails/time_zone.rb', line 74 def autocorrect(node) lambda do |corrector| # add `.zone`: `Time.at` => `Time.zone.at` corrector.insert_after(node.children[0].source_range, '.zone') case node.method_name when :current # replace `Time.zone.current` => `Time.zone.now` corrector.replace(node.loc.selector, 'now') when :new autocorrect_time_new(node, corrector) end # prefer `Time` over `DateTime` class corrector.replace(node.children.first.source_range, 'Time') if strict? remove_redundant_in_time_zone(corrector, node) end end |
#on_const(node) ⇒ Object
65 66 67 68 69 70 71 72 |
# File 'lib/rubocop/cop/rails/time_zone.rb', line 65 def on_const(node) mod, klass = *node # we should only check core classes # (`Time` or `::Time`) return unless (mod.nil? || mod.cbase_type?) && method_send?(node) check_time_node(klass, node.parent) if klass == :Time end |