Local variable ternary assignment in slim

I have a thin partial, for example:

- name = (defined?(name) ? name : 'tags') - id = (defined?(id) ? id : ('input-' + name)) - label = defined?(label) ? label : nil - placeholder = defined?(placeholder) ? placeholder : nil - className = defined?(className) ? className : nil - prefetch = defined?(prefetch) ? prefetch : nil - displayKey = defined?(displayKey) ? displayKey : nil - valueKey = defined?(valueKey) ? valueKey : nil .input-container.tags - if label label for="#{id}" = label input type="text" id="#{id}" name="#{name}" placeholder="#{placeholder}" data-prefetch="#{prefetch}" data-displayKey="#{displayKey}" data-valueKey="#{valueKey}" 

When I use it (via == render) and skip the locales inside - everything is fine.

But when I omit, for example, a name, it does not assign "tags" by default. And the same goes for id. They are just empty. If I comment on the assignment at the beginning, the error of the variable is undefined, as expected.

What is wrong with the appointment?

+5
source share
1 answer

You do not need thin. Just irb code:

 name = (defined?(name) ? name : 'tags') p name #=> nil 

This does not work because you implicitly define name on the left side of the name = ... statement. Therefore, when the Ruby interpreter evaluates defined?(name) , it really gives the result.

I think you have already received the answer:

 unless defined?(name) name = 'tags' end 

or shorter:

 name ||= 'tags' 
+3
source

All Articles