0

I have a page where I called my shared component

<%= render 'headers', positionRight: true, ...}  %>

I want to make positionRight parameter as an optional parameter. In my shared component I couldn't get the css working

<section class=<%= (defined? positionRight && positionRight) ? "custom-css-class" : "" %>>

It looks like it always fall into the empty css class

4 Answers 4

1

The above scenario can be handled the following way:

<% positionRight||= false %>
<section class=<%= positionRight ? "custom-css-class" : "" %>>

and then

<%= render 'headers', positionRight: true, ...}  %>
OR
<%= render 'headers', ...}  %>
Sign up to request clarification or add additional context in comments.

Comments

1

I'd expect it to always give you custom-css-class. (defined? positionRight && positionRight) to always evaluate to 'expression' regardless of what value (if any) positionRight has. Remember that defined? isn't a method call, it is a keyword and you're giving it an expression.

You'd be better off saying something like this at the top of your ERB file:

<%
  if !defined? positionRight
    positionRight = false
  end
%>

so that positionRight will always have a value and then

<section class=<%= positionRight ? 'custom-css-class' : '' %>>

when you want to use.

Comments

1

First, defined? something will return type of something, and in this case something is positionRight && positionRight that mean this is an "expression", so your logic will fall into "custom-css-class" not empty css as you said, since "expression" ? will always fall into truthy case.

Second, your logic just has 2 cases: true or the rest (false, nil), so no matter you set positionRight (true, false) or not set, the code below should ok:

positionRight ? "custom-css-class" : ""

Last but not least, in case you want more than 3 cases: positionRight is defined: true or false or even nil, and positionRight is not defined, then you now could use defined? as below code:

defined?(positionRight) ? (positionRight ? "css-align-right" : "css-align-left") : ""

Comments

1

In your view add this as first row of file:

<% positionRight ||= false %>
<% section_class = positionRight ? 'custom-css-class' : '' %>

And now you can use your section_class anywhere in the file:

<section class='<%= section_class %>' >...

Please, pay attention to definition of class in section element. You have to use single quotes, otherwise if your class name will include spaces, result html element will be invalid.

As well, pay attention that you variable positionRight named not in ruby style (in ruby usually they uses snakecase => position_right would be more semantic)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.