开发者

rails, method, I need help

开发者 https://www.devze.com 2022-12-22 01:49 出处:网络
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 attrib开发者_JS百科ute for a product.And to skip a step in the checkout process I nee

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 attrib开发者_JS百科ute 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:

checkout_steps.delete "registration" if current_user

It's not the way current_user returns 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:

<statment> if <condition> # only execute <statement> if <condition> is true

instead of the more traditional way:

if <condition> then
  <statement>
end

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 do

checkout_steps.delete 'shipping' if !@product.can_be_shipped

Rails supports another syntax for testing whether the condition evaluates to false:

<statment> unless <condition> # only execute <statement> if <condition> is false

Which could be used to make the logic clearer:

checkout_steps.delete 'shipping' unless @product.can_be_shipped


Try this:

def current_user
  current_user_session.user if current_user_session
end

def signed_in?
  current_user_session && !current_user_session.user.nil?
end

Then I'd rewrite your check_steps to be:

checkout_steps.delete "registration" if signed_in?

I hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号