Rails - динамически переключать подтверждающие сообщения в link_to - PullRequest
1 голос
/ 20 мая 2011

Я столкнулся с этим уродливым дублированием, чтобы вывести на экран другое подтверждающее сообщение.

<% if current_user.password.nil? and current_user.services.count == 1 %>
  <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => 'Remove this service will delete your account, are you sure?', :method => :delete %>
<% else %>
  <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => 'Are you sure you want to remove this authentication option?', :method => :delete %>
<% end %>

Я был бы рад узнать, есть ли способ избежать этого?

Спасибо!

EDIT:

ActionView::Template::Error (/Users/benoit/rails_projects/website/app/views/services/index.html.erb:15: syntax error, unexpected ',', expecting ')'
...e this authentication option?', :method => :delete, :class =...
...                               ^):
    12:         <% for service in @services %>
    13:           <div class="service">
    14:             <%= image_tag "logo_#{service.provider}.png", :class => "left" %>
    15: <%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %>
    16: 
    17:             <div class="clear"></div>
    18:           </div>

Ответы [ 2 ]

4 голосов
/ 20 мая 2011

Просто выполните:

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?', :method => :delete, :class => "remove" %>

Или, если вам это более понятно:

<% confirm_message = current_user.password.nil? and current_user.services.count == 1 ? 'Remove this service will delete your account, are you sure?' : 'Are you sure you want to remove this authentication option?' %>

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => confirm_message, :method => :delete, :class => "remove" %>

Я использую троичный оператор Ruby, отметьте его: http://invisibleblocks.wordpress.com/2007/06/11/rubys-other-ternary-operator/

3 голосов
/ 21 мая 2011

Вы можете сделать вспомогательную функцию:

def auth_confirm_delete(current_user)
  if current_user.password.nil? and current_user.services.count == 1
      'Remove this service will delete your account, are you sure?'
  else 
      'Are you sure you want to remove this authentication option?'
  end
end 

и тогда выглядит лучше:

<%= link_to "Disconnect #{service.provider.capitalize}", service, :confirm => auth_confirm_delete, :method => :delete %>
...