Is there a built-in way to conditionally add an attribute in Ruby?

In Rails, there are several times when I would like to add an attribute to something only if the attribute has a specific value.

Let me give you an example. Let's say I want to disable a button based on a specific property, for example check_if_user_can_be_added:

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

It all looks good and good, except that disabled can be applied to HTML no matter what value you give it. If you give the button an attribute disabled: false, 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 I can do it

Getting this means that you need a solution like the following, which first sets up a hash of parameters, and then passes it afterwards:

options = user_can_be_added? ? {disabled: true} : {}
link_to 'Create account', new_user_path, options

The way I would like to do this ...

, Ruby. , - . ,

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

, , - splat, ??

+4
5

nil, Rails :

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

|| :

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

, inline, ruby:

(condition ? true : false)

, :

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

, , nil disable: true, user_can_be_added? false.

, link_to . , disabled: false , link_to , html. disabled html , <a href="" disabled> . - , .

0

Rails HTML, - Github. html- :

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

Rails, , , , .

0

splat :

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

-, .

, to_h (Ruby 2.0 +):

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

For me it looks like a great place to use an assistant

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 ERB, it's just link_to_create_account(user_can_be_added?)

Not everyone likes helpers, but they work for me.

0
source

Source: https://habr.com/ru/post/1541788/


All Articles