Reputation: 986
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
Upvotes: 0
Views: 828
Reputation: 1907
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)
Upvotes: 1
Reputation: 23661
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', ...} %>
Upvotes: 1
Reputation: 3811
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") : ""
Upvotes: 1
Reputation: 434595
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.
Upvotes: 1