0

I have a Author class and need to make some validations before initializing

class Author
  include Validations

  attr_accessor :name, :biography
  

  def initialize(name, biography = nil)
    validate_author

    @name = name
    @biography = biography
  end

  def to_s
    "#{name}\n#{biography}"
  end
end

I use module for this

module Validations
  def validate_author
    raise ::StandardError, 'Name is required' if name.strip.empty?
  end 
end

And i get this error

extentions/validations.rb:8:in `validate_author': undefined method `strip' for nil:NilClass (NoMethodError)

It's ruby application

2
  • You tagged your questions with ruby-on-rails. I wonder why you are implementing validations yourself and do not use ActiveModel::Validations? Commented Apr 21, 2021 at 10:05
  • I would recommend having a look into the DRY ecosystem, which includes dry validations - dry-rb.org/gems/dry-validation/1.5 Commented Apr 21, 2021 at 12:21

3 Answers 3

1

The error gives you the clue, "for nil:NilClass (NoMethodError)", you can't apply the method .split to a Nil, what's happening that you are not passing anything so @name is nil by default, i don't know the rest of the code, but one think that you can do is use the "||" conditional writing something like.

raise ::StandardError, 'Name is required' if name.strip.empty? || name == nil
Sign up to request clarification or add additional context in comments.

Comments

0

Name is not yet assigned

class Author
  include Validations

  attr_accessor :name, :biography


  def initialize(name, biography = nil)

    @name = name
    @biography = biography
    validate_author
  end

  def to_s
    "#{name}\n#{biography}"
  end
 end

Or you can pass name to validate_author(name)

Comments

0

I think because the validate_author runs before setting the name instance variable. So if you move validate_author after setting instance variables, then it should work. However undefined method strip' for nil:NilClass (NoMethodError)` will still be raised as long name is nil.

1 Comment

The thing is that if i just put raise ::StandardError, 'Name is required' if name.strip.empty? before assignment then it works too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.