Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling an undefined variable

I render a partial in one view:

<%= render 'video', :video => @video, :video_id => 'video_show_id' %>

and have this code in the partial:

<% if video_id %>
  <%= link_to "video", video.video_url, :class => "oembed", :id => video_id %>
<% else %>
  <%= link_to "video", video.video_url, :class => "oembed" %>
<% end %>

The problem is that this partial gets rendered in a number of places in my app, and in those other views I do not want to pass :video_id into the partial. Therefore my app throws an error that video_id is undefined. I could pass :video_id => "" into the partial in the other views, but since the partial is rendered in many places, that is kind of a pain. Is there a simpler way to handle this?

like image 700
Justin Meltzer Avatar asked May 25 '11 20:05

Justin Meltzer


People also ask

How do you define an undefined variable?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

How do you handle undefined in TypeScript?

TypeScript has a powerful system to deal with null or undefined values. By default null and undefined handling is disabled, and can be enabled by setting strictNullChecks to true.

What happens when you try to access the value of an undefined variable?

Answer. You'd get an error trying to access the cat object's color property because cat itself was never defined.


1 Answers

Try defined? and not that it really matters but it's actually an operator.

<% if defined? video_id %>
like image 178
Jonas Elfström Avatar answered Nov 16 '22 02:11

Jonas Elfström