rubocop 应用程序控制器函数验证参数整数是否使用 nil?谓词

rubocop app controller function validate param integer use of nil? predicate

我尝试用多种方法重写这个函数来解决这个错误,但是,在我禁用 cop 解决它之前,我想听取其他专家的意见。

  def numeric?(obj)
    obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
  end

这是这样使用的:

  def index
    if params[:job_id] && numeric?(params[:job_id])

此问题已通过以下方式解决:Checking if a variable is an integer

正在尝试更新:

  def numeric?(string)
    !!Kernel.Float(string)
  rescue TypeError, ArgumentError
    false
  end

引用How do I determine if a string is numeric?

新错误:

你可以写方法

def numeric?(obj)
  obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/).nil?
end

您真的不需要进行 nil 比较,然后根据返回 true/false 的决定。 #nil? 方法为您完成。

下面的代码片段可以解决问题:

def numeric?(arg)
  return false if arg.is_a?(Float)
  return !Integer(arg).nil? rescue false
end

Returns 对于以下内容为 false:'a'12.34'12.34'

Returns 适用于以下情况:'1'1.

def numeric?(arg)
  !/\A[+-]?\d+\z/.match(arg.to_s).nil?
end

通过默认配置的所有 Rubocop 测试。在 https://gist.github.com/aarontc/d549ee4a82d21d263c9b

进行测试的完整要点