I need to write a method that returns whether or not a Boolean is set to true/false.
In my case the boolean is an attribute for a product. And to skip a step in the checkout process I need to have this self method work similar to the following:
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
this example is from the application_controller, and is doing the same thing in the checkout process that I need to do here.
The use for this once I have it working is:
def checkout_steps
checkout_steps = %w{registration billing shipping shipping_method payment confirmation}
checkout_steps.delete "registration" if current_user
checkout_steps
end
I need a boolean that works the same as the delete item above. I am trying to learn how this works so any explanation is greatly appreciated to.
thoughts?
I’m not quite sure I follow your question, but if you’re asking how this line works:
It’s not the way
current_userreturns its value that’s doing it. It’s a built-in syntax of Ruby where you can specify one line if statements in the following form:instead of the more traditional way:
As will the full if/end syntax, Ruby will only evaluate the statement if the condition is true, and the condition can be any code you might normally place in an if condition.
In your case, if the product’s attribute is something like
can_be_shipped, indicating whether the item can be shipped you can simply doRails supports another syntax for testing whether the condition evaluates to false:
Which could be used to make the logic clearer: