Friday, April 5, 2013

Using Rails’ New I18n Support in Real Life: Part the Second


December 12th, 2008 By: Daniel

A few more thoughts on handling I18n for real projects.
Images
The way I handled images was pretty simple. Just added this application_helper:
  # Translated image tag
  def timage_tag(source, options = {})
    image_tag("#{I18n.locale}/#{source}", options)
  end
Then I created a directory in public/images for each of the supported locales (e.g. public/images/en-US), put all the images with text in there and I was good to go.

Pagination
Pagination was handled similarly with a helper to wrap the call to mislav’s will_paginate gem:
  # Translated will_paginate
  def twill_paginate(collection = nil, options = {})
    will_paginate collection, {:previous_label => t('constants.will_paginate.previous'), :next_label => t('constants.will_paginate.next')}.merge(options)
  end
# config/locales/en-US.yml
en-US:
  constants:
    will_paginate:
      previous: "« Previous"
      next: "Next »"

activerecord
Oh and another thing that really helped was using the human_name stuff built in to activerecord. So, for example, everywhere I found an “Agent” in the text instead of an explicit call to translate I could just doAgent.human_name. And for each of Agent’s attributes I could do Agent.human_attribute_name(’name’). And that even works when it’s not a real attribute, but just one of Agent’s public methods (or anything else for that matter). Plus it’ll work for your form labels too, once you install the i18n label plugin. (One caveat though: label User, :username won’t work. It has to be a form_for(@user) do |f| and then yourf.label :username will show the human_attribute_name).
#config/locales/en-US.yml
en-US:
  activerecord:
    models:
      agent: "Agent"
    attributes:
      agent:
        name: "Name"
        some_calculated_value: "Some Calculated Value"

4 Responses to “Using Rails’ New I18n Support in Real Life: Part the Second”

  1. Moki Systems Blog » Using Rails’ New I18n Support in Real Life: Part the FirstSays:
    [...] Interesting Google Technique Using Rails’ New I18n Support in Real Life: Part the Second [...]
  2. Peter Says:
    Thanks a lot for this!
    For me the following code worked (the previous_label wasn’t working …):
    def t_will_paginate(collection = nil, options = {})
    will_paginate collection, {:prev_label => t(’constants.will_paginate.previous’),
    :next_label => t(’constants.will_paginate.next’)}.merge(options)
    end
  3. gemini Says:
    my project requires a very odd situation.
    how can i put the next button at the left side?
    and also, how can i put square brackets before the first link and after the last link which the user can not click.
    eg. the page should look like this
    Next> [ 1 2 3 4 5 ]
    thanks in advance
  4. Daniel Says:
    @gemini Sounds like you need to customize the will_paginate helpers.

No comments:

Post a Comment