Sha256: 1c5ffc2391683ac9d595c90c8e0eb86c6418de50957804eb69f50441d49b32e3

Contents?: true

Size: 1.7 KB

Versions: 11

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

require "active_support/concern"

module Decidim
  # Common logic to switch between locales.
  module LocaleSwitcher
    extend ActiveSupport::Concern

    included do
      before_action :set_locale
      helper_method :current_locale, :available_locales, :default_locale

      # Sets the locale for the current session.
      #
      # Returns nothing.
      def set_locale
        locale = if params["locale"]
                   params["locale"]
                 elsif current_user && current_user.locale.present?
                   current_user.locale
                 end

        I18n.locale = available_locales.include?(locale) ? locale : default_locale
      end

      # Adds the current locale to all the URLs generated by url_for so users
      # experience a consistent behaviour if they copy or share links.
      #
      # Returns a Hash.
      def default_url_options
        return {} if current_locale == default_locale.to_s

        { locale: current_locale }
      end

      # The current locale for the user. Available as a helper for the views.
      #
      # Returns a String.
      def current_locale
        @current_locale ||= I18n.locale.to_s
      end

      # The available locales in the application. Available as a helper for the
      # views.
      #
      # Returns an Array of Strings.
      def available_locales
        @available_locales ||= (current_organization || Decidim).public_send(:available_locales)
      end

      # The default locale of this organization.
      #
      # Returns a String with the default locale.
      def default_locale
        @default_locale ||= (current_organization || Decidim).public_send(:default_locale)
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
decidim-core-0.14.4 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.14.3 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.14.2 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.14.1 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.13.1 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.12.2 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.13.0 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.12.1 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.13.0.pre1 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.12.0 app/controllers/concerns/decidim/locale_switcher.rb
decidim-core-0.12.0.pre app/controllers/concerns/decidim/locale_switcher.rb