Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is nil in a view in Ruby?

I would like to display a line of text only if an object called @foo is set. In my view, I'm trying something like this:

<% if [email protected]_record? || [email protected]? %>
    Foo is not a new record or nil
<% end %>

But this fails, returning You have a nil object when you didn't expect it! I'm pretty sure this happens because of the new_record? method. How do I check if something is not a new record or nil without causing an error? In PHP, it would be achieved by asking if(!empty($foo)) but even the empty? method in rails causes the same error to be returned.

Any ideas?

like image 449
Yuval Karmi Avatar asked Feb 27 '10 04:02

Yuval Karmi


People also ask

What is the data type of nil in Ruby?

Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers.

Is an empty string always nil in Ruby?

That means that an empty string is NOT nil and an empty array is NOT nil. Neither is something that is false nil. => NilClass nil.nil? => true "".nil? => false false.nil? => false [].nil? For more info on .nil and NilClass, check out this sweet Ruby Guides article! .empty? [RUBY] .empty means that the length object you are trying to evaluate == 0.

How to check if an object is null in Ruby?

Calling methods on a null object causes the NullPointerException to be thrown. In C, operating on invalid pointer may lead to unexpected results. As you may expect, there should be a Ruby way to check if object is nil. Here it is: # Ruby code # if my_object. nil ? puts "There is no object!"

What is true and false in Ruby?

In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby. Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true.


1 Answers

How about:

<% if [email protected]? && [email protected]_record? %>
  Hello!
<% end %>

First off, you need to be using AND logic rather than OR logic here, since any ActiveRecord object meets at least one the requirements of "not nil" or "not a new record".

Second, checking for nil first ensures that the second check isn't run if the first one fails. The error is thrown because you can't use #new_record? on an object that doesn't support it, so checking for nil first ensures that that method is never run on a nil.

like image 196
Matchu Avatar answered Oct 12 '22 12:10

Matchu