Ruby Methods: how to return a usage string if no arguments

After I created a serious group of classes (using the initialization methods), I load them into IRb to test each of them. I do this by creating simple instances and calling their methods to find out their behavior. However, sometimes I don’t remember exactly in which order I had to give arguments when I call the .new method in the class. This requires me to take a look at the code. However, I think it should be easy enough to return a usage message instead of seeing:

ArgumentError: wrong number of arguments (0 for 9)

Therefore, I prefer to return a string with human-readable arguments, for example, using "puts" or simply returning a string. Now I saw the rescue keyword inside the source code, but I wonder how I could catch an ArgumentError when calling the initialize method.

Thanks for your answers, feedback and comments!

+3
source share
1 answer

You can connect to the creation of an object by overriding a method Class#new, for example.

class Class
  # alias the original 'new' method before overriding it
  alias_method :old_new, :new
  def new(*args)
    return old_new(*args)
    rescue ArgumentError => ae          
      if respond_to?(:usage)
        raise ArgumentError.new(usage)
      else 
        raise ae
      end
  end
end

override new, ArgumentError, usage, ArgumentError , ArgumentError.

. Person:

class Person
  def initialize(name, age)
  end

  def self.usage
    "Person.new should be called with 2 arguments: name and age"
  end
end

:

irb(main):019:0> p = Person.new
ArgumentError: Person.new should be called with 2 arguments: name and age
    from (irb):8:in `new'
    from (irb):22

: . , , ArgumentError, , - , , initialize, . , .

+4

Source: https://habr.com/ru/post/1741100/


All Articles