Search code examples
ruby-on-railsrefactoringrubocopruby-style-guide

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


I tried rewriting this function numerous ways to get around this error, however, I want to defer to other experts before I disable the cop around it.

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

This is used like so:

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

This issue was solved via: Checking if a variable is an integer

enter image description here

Update trying:

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

Reference How do I determine if a string is numeric?

New error: enter image description here


Solution

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

    Passes all Rubocop tests from a default configuration. Complete gist with tests at https://gist.github.com/aarontc/d549ee4a82d21d263c9b