Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROR + Error nil.empty? while running code

My "Project" Table have invoice as integer attribute, Here I put nil object to this attribute in DB. During evaluation nil.empty? occurs. Code written at HAML extentions

- @project.each do |proj|
  =proj.invoice if !proj.invoice.blank? || !proj.invoice.empty? || !proj.invoice.nil?
  - @project_invoice=proj.invoice

  =@project_invoice=0 if proj.invoice.blank? || proj.invoice.empty? || proj.invoice.nil

I receive this error while running code.

NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.empty?

like image 678
Rubyist Avatar asked Aug 27 '26 01:08

Rubyist


1 Answers

There's a few standard tests provided by Ruby and rails that can help, but you usually don't need to use all of them at once:

# Rails provided Object#blank? method
nil.blank? # => true
false.blank? # => true
''.blank? # => true
[ ].blank? # => true

# Ruby provided Object#nil? method
nil.nil? # => true
false.nil? # => false
''.nil? # => false
[ ].nil # => false

# Ruby class-specific #empty? method
nil.empty? # => error
false.empty? # => error
''.empty? # => true
[ ].empty? # => true

In your case the test you're probably looking for is actually a different one altogether. The opposite of blank? is present? and it comes in very handy for situations like this. You can even collapse down both of your inverted logical tests into a simple ternary query:

- @project_invoice = proj.present? ? proj.invoice : 0

More verbosely it looks like this:

- if (proj.present?)
  @project_invoice = proj.invoice
- else
  @project_invoice = 0

The present method verifies that the variable represents a non-nil, non-blank value of some sort.

like image 160
tadman Avatar answered Aug 28 '26 16:08

tadman