class RuboCop::Cop::Rails::RelativeDateConstant

This cop checks whether constant value isn't relative date. Because the relative date will be evaluated only once.

@example

# bad
class SomeClass
  EXPIRED_AT = 1.week.since
end

# good
class SomeClass
  def self.expired_at
    1.week.since
  end
end

Constants

MSG
RELATIVE_DATE_METHODS

Public Instance Methods

on_casgn(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 26
def on_casgn(node)
  _scope, _constant, rhs = *node

  # rhs would be nil in a or_asgn node
  return unless rhs

  check_node(rhs)
end
on_masgn(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 35
def on_masgn(node)
  lhs, rhs = *node

  return unless rhs && rhs.array_type?

  lhs.children.zip(rhs.children).each do |(name, value)|
    check_node(value) if name.casgn_type?
  end
end
on_or_asgn(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 45
def on_or_asgn(node)
  lhs, rhs = *node

  return unless lhs.casgn_type?

  check_node(rhs)
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 76
def autocorrect(node)
  _scope, const_name, value = *node
  indent = ' ' * node.loc.column
  new_code = ["def self.#{const_name.downcase}",
              "#{indent}#{value.source}",
              'end'].join("\n#{indent}")
  ->(corrector) { corrector.replace(node.source_range, new_code) }
end
check_node(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 55
def check_node(node)
  return unless node.irange_type? ||
                node.erange_type? ||
                node.send_type?

  # for range nodes we need to check both their boundaries
  nodes = node.send_type? ? [node] : node.children

  nodes.each do |n|
    if relative_date_method?(n)
      add_offense(node.parent, message: format(MSG, n.method_name))
    end
  end
end
relative_date_method?(node) click to toggle source
# File lib/rubocop/cop/rails/relative_date_constant.rb, line 70
def relative_date_method?(node)
  node.send_type? &&
    RELATIVE_DATE_METHODS.include?(node.method_name) &&
    !node.arguments?
end