Enrichments (e9s) for a pluggable CMS, internationalization (i18n) and localized pluralization

40
3
Ruby

h1. E9s

Enrichments (e9s) for a pluggable CMS frontend, internationalization (i18n) and localized pluralization

h2. Introduction

E9s was created due to the need of simply implementing I18n within a Rails application. This simplifies internationalization of your Rails application making a Rails developers life much easier. E9s is divided into modules (as gem and plugin): “Rich-CMS”:http://github.com/archan937/rich_cms , “Rich-i18n”:http://github.com/archan937/rich_i18n and “Rich-pluralization”:http://github.com/archan937/rich_pluralization. A list of E9s’ features:

h3. Pluggable CMS

  • @Easy setup@ - Rich-CMS only has a two-liner setup
  • @Authentication@ - Easily specify the authentication logic to be used
  • @Add editable content@ - Easily specify content available within the CMS by registering them

h3. I18n

  • @Translate on-site@ - Just specify you want to use Rich-CMS and you are set to translate in the front-end
  • @Localized pluralization@ - Translations only in singular form are sufficient enough as E9s can pluralize in foreign languages
  • @Default values@ - Use the translation key (or a portion) as default value: @“continue”.t@ returns @“continue”@ and @“text.Welcome_to_our_site”.t@ returns @“Welcome to our site”@
  • @An easy interface@ - Just call the @t@ method on string or symbols to translate and @pl@ to pluralize
  • @Combine translations@ - Joining keys with spaces combines translations: @“More houses”.t@ returns @“Meer huizen”@ in Dutch
  • @Preserve i18n meta data@ - Rich-i18n preserves the translation @key@, @value@, @locale@ and @derivative key@ (the argument passed for translation). Enquiring this can come in handy when implementing an internationalization CMS (see “Rich-CMS”:http://github.com/archan937/rich_cms).

h3. Formtastic

  • @Labels, seatholders and default values@ - Not only translate labels, but also hint text (so called @seatholders@) and even translate default values
  • @Unobtrusive implementation@ - Translate labels and seatholders unobtrusively, in other words: leave your @semantic_form_for@ (view) code completely untouched
  • @Specific translations@ - Not only specify general translations for labels and seatholders, but make them model or even form specific

h3. Inflections

  • @Preserve character casing@ - E9s preserves the casing in your translations: @“save”.t@ returns @“bewaar”@, @“Save”.t@ returns @“Bewaar”@ and @“SAVE”.t@ returns @“BEWAAR”@ in Dutch
  • @Preserve pluralization@ - E9s singularizes or pluralizes your translations depending on the key: @“house”.t@ returns @“huis”@ and @“Houses”.t@ returns @“Huizen”@ in Dutch

h2. Installation

h3. Using E9s as gem in Rails 3

Add E9s in @Gemfile@ as a gem dependency:

  gem "e9s"

Run the following in your console to install with Bundler:

  sudo bundle install

h3. Using E9s as gem in Rails 2

Add E9s in @environment.rb@ as a gem dependency:

  config.gem "e9s"

Run the following in your console:

  sudo rake gems:install

h3. Using E9s as plugin in Rails 3

  rails plugin install git://github.com/archan937/e9s.git

h3. Using E9s as plugin in Rails 2

  script/plugin install git://github.com/archan937/e9s.git

h3. Testing E9s out-of-the-box

Run the Rails console:

h4. In Rails 3

  rails c

h4. In Rails 2

  ./script/console

Start translating in Dutch:

  >> I18n.locale = :nl
  => :nl
  >> "Male / Female".t.to_s
  => "Man / Vrouw"
  >> "MORE HOUSES".t.to_s
  => "MEER HUIZEN"

h2. Use the provided Rails generator

In order to manage translations and/or CMS content. You need the following entities:

  • An @Authlogic@ authenticated user model
  • An @ActiveRecord@ model used for translation storage
  • An @ActiveRecord@ model used for CMS content storage

Fortunately, E9s is provided with a Rails generator with which you can generate all the entities.

h4. In Rails 3

Run the following in your console:

  rails g enrichments -m

Note: The generator has the @-m@ or @–migrate@ option which runs @rake db:migrate@ after creating the files.

Actually, this generator calls the generators of “Rich-CMS”:http://github.com/archan937/rich_cms and “Rich-i18n”:http://github.com/archan937/rich_i18n. For more information, please check the README files.

h4. In Rails 2

Run the following in your console:

  script/generate enrichments -m

h2. Start specifying translations

h3. Populating config/locales

At default, I18n uses @I18n::Backend::Simple@ of which translations are stored within YAML files located in @config/locales@. When adding a new language, it is adviced to copy a YAML file from “http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale”:http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale in which you can add your translations. Of course, you can also use other I18n backends like @I18n::Backend::ActiveRecord@ for translations stored in the database.

h3. Words

As E9s automatically singularizes or pluralizes the translation (depending on the passed key), you only have to specify translations in singular form.

Note: specified in @config/locales/nl.yml@

---
nl:

  word:
    "yes":   ja
    "no":    nee
    house:   huis
    letter:  brief
    sign:    teken
    user:    gebruiker
    more:    meer

h3. Pluralization

A very powerful feature of E9s is pluralization which resembles the inflections of @ActiveSupport::Inflector@. Unfortunately, specifying inflections within @config/initializers/inflections.rb@ also influences your Rails application and thus causes great problems.

E9s provides you to specify pluralization rules for different locales. You have to use regular expressions in order to specify them.

Note: specified in @config/locales/nl.yml@

---
nl:

  e9s:
    singular:
      - rule:          en$
        replacement:   ""

    plural:
      - rule:          ee$
        replacement:   eeën

      - rule:          heid$
        replacement:   heden

      - rule:          (c|m|n|t)us$
        replacement:   \1i

      - rule:        | abc, acme, acne, (a|ë|i|o|u|y)$
        replacement:   \1's
        exceptions:    (ai|eau|ei|li|lieu|ooi|ou|shampoo|spray|vlo)$

      - rule:          (blad|kind)$
        replacement:   \1eren
        exceptions:    (aanrecht|advertentie)blad

      - rule:          (e|em|el|er|erd|aar|aard|um|eur|foon|oor|ier|en|ie|eau|show|festival|é)$
        replacement:   \1s

      - rule:        | (a|e|o|u)\1([^aeiou])$
        replacement:   \1\2en

      - rule:        | (aï|alia)(s),
                       ([^aeiou][aeiou])([^aeiou])$
        replacement:   \1\2\2en
        exceptions:    dal, pad, slot, vat, weg,
                       (blad|dag|dak|engel|gat|weg)$

      - rule:          f$
        replacement:   ven

      - rule:          s$
        replacement:   zen

      - rule:          $
        replacement:   en

    irregular:
      gelid:           gelederen

    uncountable:
      - geld
      - informatie
      - rijst

For a complete example, please open “http://github.com/archan937/rich_pluralization/blob/master/locales/nl.yml”:http://github.com/archan937/rich_pluralization/blob/master/locales/nl.yml which contains Dutch inflections.

h3. Labels and seatholders

You can translate @labels@ and @seatholders@ (placeholders 😄) within Formtastic forms without altering its code.

Note: specified in @config/locales/nl.yml@

---
nl:

  word:
    password:       wachtwoord

  label:
    user_name:      gebruikersnaam
    content:        bericht

    Question:
      content:      jouw vraag

    Answer:
      content:      jouw antwoord

    (search_form)
      criteria:     uw zoekcriteria

  seatholder:
    email_address:  [email protected]

    Question:
      content:      Hoeveel uren zitten in een dag?

    Answer:
      content:      24 uur

    (search_form)
      criteria:     '&Voorbeeld'

h2. Start translating / pluralizing

h3. String / Symbol methods

E9s adds the following methods to strings and symbols:

  • @t@ - which translates the string or symbol
  • @pl@ - which pluralizes the string or symbol with inflections of the current I18n locale

Further more, E9s has enriched the String class with other inflection methods such as @upcase_first@, @cp_case@, @upcase_first!@ and @pluralize!@. Please visit “http://github.com/archan937/rich_i18n/blob/master/lib/rich/i18n/core/string/inflections.rb”:http://github.com/archan937/rich_i18n/blob/master/lib/rich/i18n/core/string/inflections.rb to see all the methods.

h3. Default values and case preservation

When not specified, E9s returns a default value based on the passed key: it splits the key on @“.”@ and (sort of) humanizes the last part. Sort of, because it actually replaces @“_”@ with @" "@ and it copies the casing of the key with the @cp_case@ method of the @String@ class.

h3. Combined keys

You can combine translations by using passed string containing translation keys joined with spaces.

h3. Translation meta data with EnrichedString

When translating text, you possibly want to know the @key@, the @value@, the @locale@ and the @derivative key@ (the argument passed for translation). Rich-i18n preserves just that in an @EnrichedString@ which is a wrapper containing meta data and the translation. Calling @.meta_data@ returns a hash with the meta data:

  >> "MORE".t.class
  => Rich::I18n::Core::EnrichedString
  >> "MORE".t.meta_data
  => {"value"=>"meer", "locale"=>:nl, "derivative_key"=>"MORE", "key"=>"word.more"}

Keep in mind that combined translations are possible and fortunately EnrichedString is able to cope with that. A concatenated translation has @merged_strings@ which contains every segments:

  >> "More streets".t.to_s
  => "Meer straten"
  >> "More answers".t.merged_strings.collect(&:to_s)
  => ["Meer", " ", "antwoorden"]
  >> "More answers".t.meta_data
  => {}
  >> "More answers".t.merged_strings.first.meta_data
  => {"value"=>"meer", "locale"=>:nl, "derivative_key"=>"More", "key"=>"word.more"}
  >> "More answers".t.merged_strings.last.meta_data
  => {"value"=>"antwoord", "locale"=>:nl, "derivative_key"=>"answers", "key"=>"word.answer"}
  >> ("one".t + " " + "question".t).to_s
  => "één vraag"
  >> ("one".t + " " + "question".t).merged_strings.collect(&:to_s)
  => ["één", " ", "vraag"]

h3. String.to_output

E9s adds the @to_output@ method to the String class. This returns the an @i18n tag@ with @HTML 5 attributes@ in which the translation meta data is provided:

  >> E9s::Engine.enable_enriched_output = true
  => true
  >> "More answers".t.to_s
  => " "

This can be very handy when implementing a CMS in which users change translations. Please note that “http://github.com/archan937/e9s-demo”:http://github.com/archan937/e9s-demo uses this feature to highlight translations. Later on this will also be used in “Rich-CMS”:http://github.com/archan937/rich_cms, a gem / plugin that makes inplace translating possible (please be patient for this to be released).

h3. I18n examples

As a result of the YAML file specified above, you will get the following translations in your Rails console:

  >> "word.house".t.to_s
  => "huis"
  >> "word.Event".t.to_s
  => "Event"
  >> "LETTERS".t.to_s
  => "BRIEVEN"
  >> "application.index.Welcome_to_our_site".t.to_s
  => "Welcome to our site"
  >> "word.users".t.to_s
  => "gebruikers"
  >> "Signs".t.to_s
  => "Tekens"
  >> "MORE USERS".t.to_s
  => "MEER GEBRUIKERS"
  >> "More houses".t.to_s
  => "Meer huizen"

h2. Render E9s in your views

h3. Alter your layout

Add the following line at the beginning of the @@ tag:

  
    <%= e9s %>
    ...
  

h3. Render CMS content

The E9s module Rich-CMS requires a rendered DOM element provided with meta data of the content instance. Fortunately, you can call a method provided by Rich-CMS. Just specify the identifier of the content type and the key of the CMS content instance in question:

  >> key = "test_content"
  => "test_content"
  >> Rich::Cms::Engine.to_content_tag(".cms_content", key)
  => "
Hello world!
"

When using a combined key for content identification, just call it as follows:

  >> Rich::Cms::Engine.to_content_tag(".cms_content", {:key => key, :locale => I18n.locale})
  => "
Hallo wereld!
"

Note: In this case, the content was registered with @Rich::Cms::Engine.register(“.cms_content”, {:class_name => “Cms::StaticContent”, :key => [:key, :locale]})@

We have also provided you a helper method to render Rich-CMS content tags:

  ...
  <%= rich_cms_tag ".cms_content", "test_content" %>
  <%= rich_cms_tag ".cms_content", {:key => "test_content", :locale => I18n.locale} %>
  ...

You can also render CMS content as HTML. When editing CMS content in Rich-CMS, a WYSIWYG editor will be displayed. Just add @:as => :html@.

  ...
  <%= rich_cms_tag ".cms_content", "application.index.welcome", :as => :html %>
  ...

For further documentation, please check the “Rich-CMS README”:http://github.com/archan937/rich_cms file.

h3. Render translations

The E9s module Rich-i18n has its own conventions which are simpler. A few examples:

  ...
  

<%= "application.index.Welcome_to_our_renewed_website".t %>

<%= link_to "PRODUCTS".t, products_path %> <%= "Hello world".t %> ...

You can also render translations as HTML. When editing translations in Rich-CMS, a WYSIWYG editor will be displayed. Just add @:as => :html@.

  ...
  <%= "application.index.welcome_text".t :as => :html %>
  ...

For further documentation, please check the “Rich-i18n README”:http://github.com/archan937/rich_i18n file.

h3. E9s in your browser

Open “http://localhost:3000/cms”:http://localhost:3000/cms, log in and start managing translations / CMS content.

h2. Contact me

For support, remarks and requests please mail me at “[email protected]:mailto:[email protected].

h2. Credit

This Rails gem / plugin depends on:

Rich-CMS

http://codehero.es/rails_gems_plugins/rich_cms”:http://codehero.es/rails_gems_plugins/rich_cms

http://github.com/archan937/rich_cms”:http://github.com/archan937/rich_cms

Rich-i18n

http://codehero.es/rails_gems_plugins/rich_i18n”:http://codehero.es/rails_gems_plugins/rich_i18n

http://github.com/archan937/rich_i18n”:http://github.com/archan937/rich_i18n

Rich-pluralization

http://codehero.es/rails_gems_plugins/rich_pluralization”:http://codehero.es/rails_gems_plugins/rich_pluralization

http://github.com/archan937/rich_pluralization”:http://github.com/archan937/rich_pluralization

h2. ToDo’s

None

h2. Enrichments

The all-in-one gem at - “http://codehero.es/rails_gems_plugins/e9s”:http://codehero.es/rails_gems_plugins/e9s - “http://github.com/archan937/e9s”:http://github.com/archan937/e9s

h3. E9s modules

h2. License

Copyright © 2010 Paul Engel, released under the MIT license

http://holder.nl”:http://holder.nl - “http://codehero.es”:http://codehero.es - “http://gettopup.com”:http://gettopup.com - “http://twitter.com/archan937”:http://twitter.com/archan937 - “[email protected]:mailto:[email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.