1 2 3 4 5 6 7 8 9 10 11 12
def translation_links lang = [ %w[en english us], %w[de deutsch], %w[cn 中国], %w[es español] ] list_items = lang.inject([]) do |sum, item| item = %(<a href="/#{item[0] unless item[0] == 'en'}" title="#{item[1]}"><img src='/flags/#{item[2]||item[0]}.gif' alt='#{item[1]}' /></a>\n) sum << item end end
Refactorings
No refactoring yet !
Adam
October 9, 2008, October 09, 2008 14:30, permalink
Not sure if you are using Rails or not. If not, just include the appropriate libraries or rewrite them yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
module TranslationHelper LANGUAGES = [ %w[en english us], %w[de deutsch], %w[cn 中国], %w[es español] ] def translation_links LANGUAGES.map do |(code,language,flag)| link_to(image_tag("/flags/#{flag || code}.gif", :alt => language), language_path(code == "en" ? nil : code)) end end end
seaofclouds
October 9, 2008, October 09, 2008 15:02, permalink
AWESOME. i like the explicit use of language to identify the parts of each string. i'm using sinatra for a site that is essentially one view, so i refactored your code slightly to achieve:
1 2 3 4 5 6 7 8 9 10 11
def translation_links languages = [ %w[en english us], %w[de deutsch], %w[cn 中国], %w[es español] ] languages.map do |(code,language,flag)| %(<a href="/#{code == "en" ? nil : code}" title="#{language}"><img src="/flags/#{flag || code}.gif" alt= "#{language}" />\n) end end
i have a simple array that i would like to iterate over, and populate an <a> tag. it's working, currently, but it looks like more work that it's worth. can it get cleaner, shorter?