Agile Web Development with Rails, Edition 5

16.4 Task K4: Add a locale switcher. 16.2 Task K2: translating the store front

16.3 Task K3: Translating Checkout

Edit the new order page

edit app/views/orders/new.html.erb
<div class="depot_form">
  <fieldset>
    <legend><%= t('.legend') %></legend>
    <%= render 'form', order: @order %>
  </fieldset>
</div>
 
<%= javascript_pack_tag("pay_type") %>

Edit the form used by the new order page

edit app/views/orders/_form.html.erb
<%= form_with(model: order, local: true) do |form| %>
  <% if order.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(order.errors.count, "error") %>
      prohibited this order from being saved:</h2>
 
      <ul>
      <% order.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
 
  <div class="field">
    <%= form.label :name, t('.name') %>
    <%= form.text_field :name, id: :order_name, size: 40 %>
  </div>
 
  <div class="field">
    <%= form.label :address, t('.address_html') %>
    <%= form.text_area :address, id: :order_address, rows: 3, cols: 40 %>
  </div>
 
  <div class="field">
    <%= form.label :email, t('.email') %>
    <%= form.email_field :email, id: :order_email, size: 40 %>
  </div>
 
  <div id='pay-type-component'></div>
 
  <div class="actions">
    <%= form.submit t('.submit') %>
  </div>
<% end %>

Install i18n-js

edit Gemfile
bundle install --local
Resolving dependencies...
Using rake 12.0.0
Using pg 0.19.0
Using ffi 1.9.18
Using concurrent-ruby 1.0.5
Using i18n 0.8.4
Using minitest 5.10.1
Using thread_safe 0.3.6
Using builder 3.2.3
Using erubi 1.6.0
Using mini_portile2 2.2.0
Using rack 2.0.3
Using nio4r 2.1.0
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 8.0.0
Using bundler 1.15.1
Using method_source 0.8.2
Using thor 0.19.4
Using sqlite3 1.3.13
Using puma 3.9.1
Using sass 3.4.24
Using tilt 2.0.7
Using execjs 2.7.0
Using coffee-script-source 1.12.2
Using turbolinks-source 5.0.3
Using multi_json 1.12.1
Using bcrypt 3.1.11
Using byebug 9.0.6
Using public_suffix 2.0.5
Using rubyzip 1.2.1
Using bindex 0.5.0
Using queue_classic 3.2.0.RC1 from source at `/home/rubys/git/queue_classic`
Using rb-inotify 0.9.9 from source at `/home/rubys/git/rb-inotify`
Using childprocess 0.7.0
Using i18n-js 3.0.0
Using tzinfo 1.2.3
Using nokogiri 1.8.0
Using rack-test 0.6.3
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using foreman 0.84.0
Using uglifier 3.2.0
Using coffee-script 2.4.1
Using turbolinks 5.0.1
Using addressable 2.5.1
Using selenium-webdriver 3.4.1
Using activesupport 5.1.1 from source at `/home/rubys/git/rails`
Using loofah 2.0.3
Using xpath 2.1.0
Using mail 2.6.6
Using rails-dom-testing 2.0.3
Using globalid 0.4.0
Using activemodel 5.1.1 from source at `/home/rubys/git/rails`
Using jbuilder 2.7.0
Using spring 2.0.2
Using rails-html-sanitizer 1.0.3
Using capybara 2.14.2
Using activejob 5.1.1 from source at `/home/rubys/git/rails`
Using activerecord 5.1.1 from source at `/home/rubys/git/rails`
Using actionview 5.1.1 from source at `/home/rubys/git/rails`
Using activemodel-serializers-xml 1.0.1
Using actionpack 5.1.1 from source at `/home/rubys/git/rails`
Using actioncable 5.1.1 from source at `/home/rubys/git/rails`
Using actionmailer 5.1.1 from source at `/home/rubys/git/rails`
Using railties 5.1.1 from source at `/home/rubys/git/rails`
Using sprockets-rails 3.2.0
Using coffee-rails 4.2.2
Using web-console 3.5.1 from source at `/home/rubys/git/web-console`
Using jquery-rails 4.3.1
Using jquery-ui-rails 6.0.1
Using webpacker 2.0
Using rails 5.1.1 from source at `/home/rubys/git/rails`
Using sass-rails 5.0.6
Bundle complete! 23 Gemfile dependencies, 74 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
edit config/application.rb
require_relative 'boot'
 
require 'rails/all'
 
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
 
module Depot
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.1
 
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
 
    config.filter_parameters += [ :credit_card_number ]
 
    config.middleware.use I18n::JS::Middleware
  end
end

Restart the server.

edit app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will
// include all the files listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or
// any plugin's vendor/assets/javascripts directory can be referenced here
// using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at
// the bottom of the compiled file. JavaScript code in this file should be
// added after the last require_* statement.
//
// Read Sprockets README
// (https://github.com/rails/sprockets#sprockets-directives) for details about
// supported directives.
//
//= require rails-ujs
//= require jquery
//= require jquery-ui/effects/effect-blind
//= require turbolinks
 
//= require i18n
//= require i18n/translations
//= require_tree .
edit app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Pragprog Books Online Store</title>
    <%= csrf_meta_tags %>
 
    <%= stylesheet_link_tag    'application', media: 'all',
    'data-turbolinks-track': 'reload' %>
    
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <script type="text/javascript">
      I18n.defaultLocale = "<%= I18n.default_locale %>";
      I18n.locale        = "<%= I18n.locale %>";
    </script>
 
  </head>
 
  <body class="<%= controller.controller_name %>">
    <div id="banner">
      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <span class="title"><%= @page_title %></span>
    </div>
    <div id="columns">
      <div id="side">
        <% if @cart %>
          <%= hidden_div_if(@cart.line_items.empty?, id: 'cart') do %>
            <%= render @cart %>
          <% end %>
        <% end %>
 
      <%= render Order.find(session[:order_id]) if session[:order_id] -%>
 
        <ul>
          <li><a href="http://www...."><%= t('.home') %></a></li>
          <li><a href="http://www..../faq"><%= t('.questions') %></a></li>
          <li><a href="http://www..../news"><%= t('.news') %></a></li>
          <li><a href="http://www..../contact"><%= t('.contact') %></a></li>
        </ul>
 
        <% if session[:user_id] %>
          <ul>
            <li><%= link_to 'Orders',   orders_path   %></li>
            <li><%= link_to 'Products', products_path %></li>
            <li><%= link_to 'Users',    users_path    %></li>
          </ul>
          <%= button_to 'Logout', logout_path, method: :delete   %>
        <% end %>
      </div>
      <div id="main">
        <%= yield %>
      </div>
    </div>
  </body>
</html>
edit app/javascript/PayTypeSelector/index.jsx
import React from 'react'
 
import NoPayType            from './NoPayType';
import CreditCardPayType    from './CreditCardPayType';
import CheckPayType         from './CheckPayType';
import PurchaseOrderPayType from './PurchaseOrderPayType';
 
class PayTypeSelector extends React.Component {
  constructor(props) {
    super(props);
    this.onPayTypeSelected = this.onPayTypeSelected.bind(this);
    this.state = { selectedPayType: null };
  }
 
  onPayTypeSelected(event) {
    this.setState({ selectedPayType: event.target.value });
  }
 
  render() {
    let PayTypeCustomComponent = NoPayType;
    if (this.state.selectedPayType == "Credit card") {
      PayTypeCustomComponent = CreditCardPayType;
    } else if (this.state.selectedPayType == "Check") {
      PayTypeCustomComponent = CheckPayType;
    } else if (this.state.selectedPayType == "Purchase order") {
      PayTypeCustomComponent = PurchaseOrderPayType;
    }
    return (
      <div>
        <div className="field">
          <label htmlFor="order_pay_type">
            {I18n.t("orders.form.pay_type")}
          </label>
 
          <select id="pay_type" onChange={this.onPayTypeSelected} 
            name="order[pay_type]">
            <option value="">
              {I18n.t("orders.form.pay_prompt_html")}
            </option>
 
            <option value="Check">
              {I18n.t("orders.form.pay_types.check")}
            </option>
 
            <option value="Credit card">
              {I18n.t("orders.form.pay_types.credit_card")}
            </option>
 
            <option value="Purchase order">
              {I18n.t("orders.form.pay_types.purchase_order")}
            </option>
 
          </select>
        </div>
        <PayTypeCustomComponent />
      </div>
    );
  }
}
export default PayTypeSelector
edit app/javascript/PayTypeSelector/CheckPayType.jsx
import React from 'react'
 
class CheckPayType extends React.Component {
  render() {
    return (
      <div>
        <div className="field">
          <label htmlFor="order_routing_number">
            {I18n.t("orders.form.check_pay_type.routing_number")}
          </label>
 
          <input type="password"
                 name="order[routing_number]" 
                 id="order_routing_number" />
        </div>
        <div className="field">
          <label htmlFor="order_acount_number">
            {I18n.t("orders.form.check_pay_type.account_number")}
          </label>
 
          <input type="text"
                 name="order[account_number]" 
                 id="order_account_number" />
        </div>
      </div>
    );
  }
}
export default CheckPayType
edit app/javascript/PayTypeSelector/CreditCardPayType.jsx
import React from 'react'
 
class CreditCardPayType extends React.Component {
  render() {
    return (
      <div>
        <div className="field">
          <label htmlFor="order_credit_card_number">
            {I18n.t("orders.form.credit_card_pay_type.cc_number")}
          </label>
 
          <input type="password"
                 name="order[credit_card_number]" 
                 id="order_credit_card_number" />
        </div>
        <div className="field">
          <label htmlFor="order_expiration_date">
            {I18n.t("orders.form.credit_card_pay_type.expiration_date")}
          </label>
 
          <input type="text"
                 name="order[expiration_date]" 
                 id="order_expiration_date"
                 size="9"
                 placeholder="e.g. 03/19" />
        </div>
      </div>
    );
  }
}
export default CreditCardPayType
edit app/javascript/PayTypeSelector/PurchaseOrderPayType.jsx
import React from 'react'
 
class PurchaseOrderPayType extends React.Component {
  render() {
    return (
      <div>
        <div className="field">
          <label htmlFor="order_po_number">
            {I18n.t("orders.form.purchase_order_pay_type.po_number")}
          </label>
 
          <input type="password"
                 name="order[po_number]" 
                 id="order_po_number" />
        </div>
      </div>
    );
  }
}
export default PurchaseOrderPayType

Restart the server.

Define some translations for the new order.

edit config/locales/en.yml
en:
 
  orders:
    new:
      legend:       "Please Enter Your Details"
    form:
      name:         "Name"
      address_html: "Address"
      email:        "E-mail"
      pay_type:     "Pay with"
      pay_prompt_html: "Select a payment method"
      submit:       "Place Order"
      pay_types:
        check:           "Check"
        credit_card:     "Credit Card"
        purchase_order:  "Purchase Order"
      check_pay_type:
        routing_number: "Routing #"
        account_number: "Account #"
      credit_card_pay_type:
        cc_number: "CC #"
        expiration_date: "Expiry"
      purchase_order_pay_type:
        po_number: "PO #"
 
edit config/locales/es.yml
es:
 
  orders:
    new:
      legend:       "Por favor, introduzca sus datos"
    form:
      name:         "Nombre"
      address_html: "Direcci&oacute;n"
      email:        "E-mail"
      pay_type:     "Forma de pago"
      pay_prompt_html: "Seleccione un método de pago"
      submit:       "Realizar Pedido"
      pay_types:
        check:           "Cheque"
        credit_card:     "Tarjeta de Crédito"
        purchase_order:  "Orden de Compra"
      check_pay_type:
        routing_number: "# de Enrutamiento"
        account_number: "# de Cuenta"
      credit_card_pay_type:
        cc_number: "Número"
        expiration_date: "Expiración"
      purchase_order_pay_type:
        po_number: "Número"

Add to cart

get /es

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 45,00 $US
Total 45,00 $US

Su Catálogo de Pragmatic

Dcbang

Rails, Angular, Postgres, and Bootstrap

Powerful, Effective, and Efficient Full-Stack Web Development As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

45,00 $US
Adrpo

Ruby Performance Optimization

Why Ruby Is Slow, and How to Fix It You don’t have to accept slow Ruby or Rails performance. In this comprehensive guide to Ruby optimization, you’ll learn how to write faster Ruby code—but that’s just the beginning. See exactly what makes Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you through perils of memory and CPU optimization, profiling, measuring, performance testing, garbage collection, and tuning. You’ll find that all those “hard” things aren’t so difficult after all, and your code will run orders of magnitude faster.

46,00 $US
7apps

Seven Mobile Apps in Seven Weeks

Native Apps, Multiple Platforms Answer the question “Can we build this for ALL the devices?” with a resounding YES. This book will help you get there with a real-world introduction to seven platforms, whether you’re new to mobile or an experienced developer needing to expand your options. Plus, you’ll find out which cross-platform solution makes the most sense for your needs.

26,00 $US
post /es/line_items?product_id=2
You are being redirected.
get http://localhost:3000/

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US

Su Catálogo de Pragmatic

Dcbang

Rails, Angular, Postgres, and Bootstrap

Powerful, Effective, and Efficient Full-Stack Web Development As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

45,00 $US
Adrpo

Ruby Performance Optimization

Why Ruby Is Slow, and How to Fix It You don’t have to accept slow Ruby or Rails performance. In this comprehensive guide to Ruby optimization, you’ll learn how to write faster Ruby code—but that’s just the beginning. See exactly what makes Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you through perils of memory and CPU optimization, profiling, measuring, performance testing, garbage collection, and tuning. You’ll find that all those “hard” things aren’t so difficult after all, and your code will run orders of magnitude faster.

46,00 $US
7apps

Seven Mobile Apps in Seven Weeks

Native Apps, Multiple Platforms Answer the question “Can we build this for ALL the devices?” with a resounding YES. This book will help you get there with a real-world introduction to seven platforms, whether you’re new to mobile or an experienced developer needing to expand your options. Plus, you’ll find out which cross-platform solution makes the most sense for your needs.

26,00 $US

Show mixed validation errors

get /es/orders/new

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US
Por favor, introduzca sus datos
post /orders

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US
Por favor, introduzca sus datos

4 error prohibited this order from being saved:

  • Name no puede quedar en blanco
  • Address no puede quedar en blanco
  • Email no puede quedar en blanco
  • Pay type no est&aacute; incluido en la lista

Translate the errors to human names.

edit config/locales/es.yml
es:
 
  activerecord:
    errors:
      messages:
        inclusion: "no est&aacute; incluido en la lista"
        blank:     "no puede quedar en blanco"
  errors:
    template:
      body:        "Hay problemas con los siguientes campos:"
      header:
        one:       "1 error ha impedido que este %{model} se guarde"
        other:     "%{count} errores han impedido que este %{model} se guarde"

Display messages in raw form, and translate error messages

edit app/views/orders/_form.html.erb
<%= form_with(model: order, local: true) do |form| %>
  <% if order.errors.any? %>
    <div id="error_explanation">
      <h2><%=raw t('errors.template.header', count: @order.errors.count,
        model: t('activerecord.models.order')) %>.</h2>
      <p><%= t('errors.template.body') %></p>
 
      <ul>
      <% order.errors.full_messages.each do |message| %>
        <li><%=raw message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
<!-- ... -->
 
  <div class="field">
    <%= form.label :name, t('.name') %>
    <%= form.text_field :name, id: :order_name, size: 40 %>
  </div>
 
  <div class="field">
    <%= form.label :address, t('.address_html') %>
    <%= form.text_area :address, id: :order_address, rows: 3, cols: 40 %>
  </div>
 
  <div class="field">
    <%= form.label :email, t('.email') %>
    <%= form.email_field :email, id: :order_email, size: 40 %>
  </div>
 
  <div id='pay-type-component'></div>
 
  <div class="actions">
    <%= form.submit t('.submit') %>
  </div>
<% end %>

Translate the model names to human names.

edit config/locales/es.yml
es:
 
  activerecord:
    models:
      order:       "pedido"
    attributes:
      order:
        address:   "Direcci&oacute;n"
        name:      "Nombre"
        email:     "E-mail"
        pay_type:  "Forma de pago"

Show validation errors

get /es/orders/new

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US
Por favor, introduzca sus datos
post /orders

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US
Por favor, introduzca sus datos

4 errores han impedido que este pedido se guarde.

Hay problemas con los siguientes campos:

  • Nombre no puede quedar en blanco
  • Dirección no puede quedar en blanco
  • E-mail no puede quedar en blanco
  • Forma de pago no está incluido en la lista

Replace translatable text with calls out to translation functions.

edit app/controllers/orders_controller.rb
  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(@cart)
 
    respond_to do |format|
      if @order.save
        Cart.destroy(session[:cart_id])
        session[:cart_id] = nil
        session[:order_id] = @order.id
        ChargeOrderJob.perform_later(@order,pay_type_params.to_h)
        format.html { redirect_to store_index_url(locale: I18n.locale), 
          notice: I18n.t('.thanks') }
        format.json { render :show, status: :created,
          location: @order }
      else
        format.html { render :new }
        format.json { render json: @order.errors,
          status: :unprocessable_entity }
      end
    end
  end

Modify the test to reflect the new redirect

edit test/controllers/orders_controller_test.rb
  test "should create order" do
    assert_difference('Order.count') do
      post orders_url, params: { order: { address: @order.address,
        email: @order.email, name: @order.name,
        pay_type: @order.pay_type } }
    end
 
    assert_redirected_to store_index_url(locale: 'en')
  end

Define some translations for the flash.

edit config/locales/en.yml
en:
 
  thanks:          "Thank you for your order"
edit config/locales/es.yml
es:
 
  thanks:          "Gracias por su pedido"

Place the order

get /es/orders/new

Carrito de la Compra

Rails, Angular, Postgres, and Bootstrap 90,00 $US
Total 90,00 $US
Por favor, introduzca sus datos
post /orders
You are being redirected.
get http://localhost:3000/es

Gracias por su pedido

Su Catálogo de Pragmatic

Dcbang

Rails, Angular, Postgres, and Bootstrap

Powerful, Effective, and Efficient Full-Stack Web Development As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

45,00 $US
Adrpo

Ruby Performance Optimization

Why Ruby Is Slow, and How to Fix It You don’t have to accept slow Ruby or Rails performance. In this comprehensive guide to Ruby optimization, you’ll learn how to write faster Ruby code—but that’s just the beginning. See exactly what makes Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you through perils of memory and CPU optimization, profiling, measuring, performance testing, garbage collection, and tuning. You’ll find that all those “hard” things aren’t so difficult after all, and your code will run orders of magnitude faster.

46,00 $US
7apps

Seven Mobile Apps in Seven Weeks

Native Apps, Multiple Platforms Answer the question “Can we build this for ALL the devices?” with a resounding YES. This book will help you get there with a real-world introduction to seven platforms, whether you’re new to mobile or an experienced developer needing to expand your options. Plus, you’ll find out which cross-platform solution makes the most sense for your needs.

26,00 $US

16.4 Task K4: Add a locale switcher. 16.2 Task K2: translating the store front