[ACCEPTED]-Is there an inline way to conditionally add an attribute in Ruby?-ruby

Accepted answer
Score: 10

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

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

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

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

I'm not familiar with rails, but inline 13 if statements can be achieved as follows 12 in ruby:

(condition ? true : false)

I would assume your code would look 11 like this:

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

This would essentially pass in 10 nil in place of disable: true if user_can_be_added? resolves to false.

I'm 9 not sure how the link_to function would handle 8 that, though. I guess the reason disabled: false doesn't 7 work, is the link_to function recieves a hash of 6 attributes as the final parameter, which 5 are applied to an html link. Since the disabled attribute 4 in html doesn't need a value, it would just 3 stick in <a href="" disabled> regardless of its value. Someone 2 feel free to correct me though, I haven't 1 used rails.

Score: 0

Years ago I used a Rails plugin for HTML 6 attributes that is still available on Github. That 5 plugin allowed to write html tags like this:

content_tag(:div, :class => { :first => true, :second => false, :third => true }) { ... }
# => <div class="first third">...

Plugins 4 are unsupported by current versions of Rails 3 and plugin only worked for tag helpers, but 2 perhaps this helps you to write a helper 1 yourself.

Score: 0

For many arguments, using the splat will 4 work:

p "Here's 42 or nothing:", *(42 if rand > 0.42)

This won't work for a hash argument 3 though, because it will convert it to an 2 array.

I wouldn't recommend it, but you could 1 use to_h (Ruby 2.0+):

link_to 'Create account', new_user_path, ({disabled: true} if user_can_be_added?).to_h
Score: 0

To me that looks like a great place to use 2 a helper

module AccountHelper 

  def link_to_create_account disabled = false
    if disabled
      link_to 'Create account', new_user_path, disabled: true
    else
      link_to 'Create account', new_user_path
    end
  end 
end

In your ERB it's simply link_to_create_account(user_can_be_added?)

Not everyone 1 likes helpers, but they work for me.

More Related questions