Skip to content
Michel Martens edited this page Apr 20, 2016 · 1 revision

If you need to translate content in your web application, you can integrate the i18n gem with Cuba.

Here's an example of how your application may look like:

# app.rb
require "cuba"
require "mote"
require "i18n"

I18n.load_path = Dir["./translations/*.yml"]
I18n.backend.load_translations
I18n.default_locale = :en

class Cuba
  include Mote::Helpers

  def t(str)
    I18n.t(str)
  end

  def render(template, params = {})
    res.write mote("./views/#{template}.mote", params)
  end

  def not_found
    res.status = 404
    res.write "Not found!"
  end
end

class SubApp < Cuba
  define do
    on root do
      on get do
        render "home"
      end
    end
  end
end

Cuba.define do
  on "es" do
    I18n.locale = :es
    
    run SubApp
  end

  on "en" do
    I18n.locale = :en
    
    run SubApp
  end

  on root do
    run SubApp
  end
end

Here's a view:

./views/home.mote

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  </head>
  <body>
    <header>
      <h1>Cuba Test</h1>
    </header>
    <section>
      <p>{{ t("greeting") }}</p>
    </section>
    <footer>
    </footer>
  </body>
</html>

And the translations file:

./translations/en.yml

en:
  greeting: "Hello!"
es:
  greeting: "Hola!"
Clone this wiki locally