Wizzard
Wizzard

Reputation: 12712

Whats this ruby function doing

In this project I poke at, (I am PHP dev, not RoR), there is this function on a modal.

  def task 
    @task ||= if search_key 
      Project.trop_fish.tasks.find(:first, :conditions => ["description like ?", "Search key: #{search_key}%"]) 
    else 
      Project.trop_fish.tasks.find(:first, :conditions => ["(name = ? OR name like ?)","#{task_name}","#{task_name} {%}"]) 
    end 
  end

So it's trying to find a task, from the project called trop_fish. But whats the @task at the top.

Is it, assign the result of the finds from the if block to the @task?

Is it the same as

  def task 
    if search_key 
      @task = Project.trop_fish.tasks.find(:first, :conditions => ["description like ?", "Search key: #{search_key}%"]) 
    else 
      @task = Project.trop_fish.tasks.find(:first, :conditions => ["(name = ? OR name like ?)","#{task_name}","#{task_name} {%}"]) 
    end 
  end

Upvotes: 1

Views: 97

Answers (1)

Batkins
Batkins

Reputation: 5716

Almost, not quite. It is the same thing as this:

def task 
  if search_key 
    @task ||= Project.trop_fish.tasks.find(:first, :conditions => ["description like ?", "Search key: #{search_key}%"]) 
  else 
    @task ||= Project.trop_fish.tasks.find(:first, :conditions => ["(name = ? OR name like ?)","#{task_name}","#{task_name} {%}"]) 
  end 
end

The ||= indicates that the variable will only be set to the new value if it is not already set with a different value. As some people commenting have pointed out/to put it more simply, @task will be set to the new value if it is nil or false.

This portion of the RoR tutorial by Michael Hartl is a great explanation of the ||= operator.

@pguardino brings up a good point in that a PHP programmer may not be familiar with the fact that if there is no explicit return statement within a method in ruby, it will return the last non-conditional statement in the method as it's return value, so yes, @task is being returned.

There is another bit of text in the RoR tutorial which explains why it is advantageous to use the ||= operator when returning from a method. It is useful because it means the first call to the task method will perform an operation against the database to retrieve a task, but subsequent calls to the method within the same thread will return @task without making calls to the database (since the @task variable has already been set.

Upvotes: 5

Related Questions