Is there an inline way to conditionally add an attribute in Ruby?

html, ruby, ruby-on-rails

Solution

You can just set nil to cause Rails to ignore the attribute:

link_to 'Create account', new_user_path, disabled: (user_can_be_added? ? true : nil)

For this particular case, you can also use || like so:

link_to 'Create account', new_user_path, disabled: (user_can_be_added? || nil)

Problem

There are a number of times in Rails when I would like to be able to add an attribute to something only if the attribute is of a particular value. Let me give you an example. Let's say I want to disable a button based on a particular property such as `check_if_user_can_be_added`: ``` link_to 'Create account', new_user_path, disabled: (user_can_be_added?) ``` This all looks fine and well except that disabled happens to be applied in HTML regardless of what value you give it. If you give a button the attribute `disabled: false` then it will still be disabled. What I need ``` # if the button is disabled link_to 'Create account', new_user_path, disabled: true # if the button is not disabled link_to 'Create account', new_user_path ``` The way that I can see to do it Getting this means that you need a solution similar to the following which sets up the options hash first and then passes it in subsequently: ``` options = user_can_be_added? ? {disabled: true} : {} link_to 'Create account', new_user_path, options ``` The way I would like to do it... This doesn't work but trusting in Ruby's beauty I suspect there's something similar out there. This is basically what I'd like to do ``` link_to 'Create account', new_user_path, ({disabled: true} if user_can_be_added?) ``` Can I do it, is there perhaps something using the splat operator that gets me there...?

Original source