Fd534d7c08b85546ce17df043ef15cd3

Hi, I'm sure this is the most horrible way I could ever do it but I just cant figure out how to insert an if statement next to a link_to class.

<% if I18n.locale == :pl %>
    <%= link_to 'PL', { :locale => :pl }, :class => "language_selected" %> | <%= link_to 'ENG', { :locale => :en } %>
<% else %>
    <%= link_to 'PL', { :locale => :pl } %> | <%= link_to 'ENG', { :locale => :en }, :class => "language_selected" %>
<% end %>

Refactorings

No refactoring yet !

4f5d54213efb6502baab202f3fb2f09e

sfusion

August 25, 2010, August 25, 2010 11:29, permalink

No rating. Login to rate!

why not plonk it in a helper?

def locale_links
  [:pl, :en].collect |locale|
    class =  (I18n.locale == locale) ? 'language_selected' : nil
    link_to locale.to_s.upcase, { :locale => locale }, :class => class
  end.join(' | ')
end
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

August 27, 2010, August 27, 2010 14:35, permalink

2 ratings. Login to rate!

I'd also put it in a helper (putting logic directly in the view isn't very nice to maintain). I would not set the html_options-hash with an empty class though... IMHO

BTW: if/unless expression can be put in parentheses and used as a parameter in method calls. Also have a look at the link_to_if and link_to_unless methods...

def locale_links
  [:pl, :en].map { |locale| link_to locale.to_s.upcase, {:locale => locale}, (:class => :language_selected if I18n.locale == locale)}.join ' | '
end
Fd534d7c08b85546ce17df043ef15cd3

Omer Jakobinsky

August 30, 2010, August 30, 2010 09:12, permalink

No rating. Login to rate!

Thanks both of you I really like the one liner and I would definitely have a look at link_to_if.

Your refactoring





Format Copy from initial code

or Cancel