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
Almost, not quite. It is the same thing as this:
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,@taskwill be set to the new value if it isnilorfalse.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
returnstatement within a method in ruby, it will return the last non-conditional statement in the method as it’s return value, so yes,@taskis 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 thetaskmethod will perform an operation against the database to retrieve a task, but subsequent calls to the method within the same thread will return@taskwithout making calls to the database (since the@taskvariable has already been set.