SlideShare ist ein Scribd-Unternehmen logo
1 von 58
before_filter :set_locale
def set_locale
    # if params[:locale] is nil then I18n.default_locale
will be used
    I18n.locale = params[:locale]
end
# app/controllers/application_controller.rb
def default_url_options(options = {})
   logger.debug “default_url_options is passed
options:
      #{options.inspect}n”
      {:locale => I18n.locale}
end
# config/routes.rb
map.resources :books, :path_prefix => '/:locale'
   # => www.example.com/nl/books
map.root '/:locale', :controller => “dashboard”
before_filter :set_locale

def set_locale
   I18n.locale = extract_locale_from_uri
end
def extract_locale_from_tld
   parsed_locale = request.host.split('.').last
   I18n.available_locales.include?
(parsed_locale.to_sym) ? parsed_locale : nil
end
def set_locale
    logger.debug = “* Accept-Language:
#{request.env['HTTP_ACCEPT_LANGUAGE']}”
    I18n.locale =
extract_locale_from_accept_language_header
end
def extract_locale_from_accept_language_header
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]
{2}/).first
end
en:
    activerecord:
       models:
           user: foo
           admin: bar
       attributes:
           user:
              login: “Handle” # => will translate User
attribute “login” as “Handle”
en:
   activerecord:
       errors:
           messages:
               blank: “can not has nottin”
# => u = User.new
# => #<User id:nil, etc>
# => u.valid?
# => false
# => u.errors.on(:name)
# => “can not has nottin”
en:
   activerecord:
      errors:
          messages:
              already_registered: “u already is
{{model}}”
# => u.errors.on(:email)
# => “u already is foo”
en:
 activerecord:
  errors:
    template:
     header:
      one: “1 error prohibted this {{model}} from being
saved”
      other: “{{count}} errors prohibted this {{model}} from
being saved”
     body: “There were problems with the following fields:”
i18n


          i18n                                   i18n




                                                        backend
backend    core_ext   helpers        locales

                                                        exceptions

                       gettext
                                                        gettext


                                                        helpers


                        tag          fallbacks          locale


                                                        version
backend



      Interpolation       fast        simple   active_record
      active_record
        compiler

      Interpolation     gettext
          base
        compiler
                                                         missing
      Interpolation     helpers
          cache
        compiler

                                                       store_procs
      Interpolation   Interpolation
        cascader        compiler
        compiler

      Interpolation      links                         translation
          chain
        compiler


      Interpolation    metadata
           cldr
        compiler

      Interpolation   pluralization
        fallbacks
        compiler
def default_locale(locale)
   @@default_locale = locale.to_sym rescue nil
end
def backend
   @@backend ||= Backend::Simple.new
end
module I18n
   module Backend
     class Simple
         include Base
     end
   end
end
def available_locales
   @@available_locales ||= backend.available_locales
end
def default_exception_handler(exception, locale, key,
options)
   return exception.message if MissingTranslationData ===
exception
   raise exception
end
def config
   Thread.current[:i18n_config] ||= I18n::Config.new
end
I18n.t :invalid, :scope =>
[:active_record, :error_messages] # =>
I18n.translation :invalid :active_record.error_messa
ges.invalid
I18n.t :foo, :bar => 'baz' #=> 'foo baz'



I18n.t :foo, :count => 1 #=> 'foo'
I18n.t :foo, :count => 0 #=> 'foos'
I18n.t :foo, :count => 2 #=> 'foos'



I18n.t :foo, :default => 'bar'
def translate(&args)
    options = args.pop if args.last.is_a?(Hash)
    key = args.shift
    locale = options && options.delete(:locale) ||
config.locale
    raises = options && options.delete(:raise)
    config.backend.translate(locale, key, options ||
{})
rescue I18n::ArgumentError => exception
    raise exception if raises
    handle_exception(exception, locale, key,
options)
end
alias :t :translate
def localize(object, options = {})
    locale = options.delete(:locale) || config.locale
    format = options.delete(:format) || :default
    config.backend.localize(locale, object, format,
options)
end
alias :l :localize
def load_translations(*filenames)
   filenames.each { |filename| load_file(filename) }
end
def load_file(filename)
     type = File.extname(filename).tr('.', '').downcase
     raise UnknownFileType.new(type, filename)
unless respond_to?(:”load_#(type)”)
     data = send(:”load_#(type)”, filename)
     data.each { |locale, d| merge_translation(locale,
d) }
end
def store_translations(locale, data, options = {})
   merge_translations(locale, data, options)
end
def merge_translations(locale, data, options = {})
   locale = locale.to_sym
   translations[locale] ||= {}
   separator = options[:separator] ||
I18n.default_separator
   data = unwind_keys(data, separator)
   data = deep_symbolized_keys(data)

   merger = proc do |key, v1, v2|
      Hash === v1 && Hash === v2 ?
         v1.merge(v2, &merger) : (v2 || v1)
   end
   translations[locale].merge!(data, &merger)
end
def translate(locale, key, options = {})
     raise InvalidLocale.new(locale) unless locale
     return key.map { |k| translate(locale, k, options) } if
key.is_a?(Array)

     if options.empty?
       entry = resolve(locale, key, lookup(locale, key),
options)
       raise(I18n::MissingTranslationData.new(locale, key,
options)) if entry.nil?
else
      count, scope, default =
options.values_at(:count, :scope, :default)
      values = options.reject { |name, value|
RESERVED_KEYS.include?(name) }

      entry = lookup(locale, key, scope, options)
      entry = entry.nil? && default ?
default(locale, key, default, options) :
resolve(locale, key, entry, options)
raise(I18n::MissingTranslationData.new(locale,
key, options)) if entry.nil?
       entry = pluralize(locale, entry, count) if
count
       entry = interpolate(locale, entry, values) if
values
    end
     entry
end
case match
      when '%a' then I18n.t(:"date.abbr_day_names”, :locale =>
locale, :format => format)[object.wday]
      when '%A' then I18n.t(:"date.day_names”, :locale =>
locale, :format => format)[object.wday]
      when '%b' then I18n.t(:"date.abbr_month_names", :locale =>
locale, :format => format)[object.mon]
when '%B' then I18n.t(:"date.month_names", :locale =>
locale, :format => format)[object.mon]
      when '%p' then I18n.t(:"time.#{object.hour <
12 ? :am : :pm}", :locale => locale, :format => format) if
object.respond_to? :hour
      end
MissingTranslationData # no translation was found for the
requested key
InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
I18n.backend = Globalize::Backend::Static.new
module I18n
  def just_raise_that_exception(*args)
     raise args.first
  end
end

I18n.exception_handler = :just_raise_that_exception
The ruby on rails i18n core api-Neeraj Kumar
The ruby on rails i18n core api-Neeraj Kumar
The ruby on rails i18n core api-Neeraj Kumar

Weitere ähnliche Inhalte

Was ist angesagt?

Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
King Hom
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
Kumar
 

Was ist angesagt? (20)

Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
 
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
Loops and Unicorns - The Future of the Puppet Language - PuppetConf 2013
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
 
Damien seguy php 5.6
Damien seguy php 5.6Damien seguy php 5.6
Damien seguy php 5.6
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
 
Lexyacc
LexyaccLexyacc
Lexyacc
 

Andere mochten auch

Sample of instructions
Sample of instructionsSample of instructions
Sample of instructions
David Sommer
 
Bank Account Of Life
Bank Account Of LifeBank Account Of Life
Bank Account Of Life
Nafass
 
My trans kit checklist gw1 ds1_gw3
My trans kit checklist gw1 ds1_gw3My trans kit checklist gw1 ds1_gw3
My trans kit checklist gw1 ds1_gw3
David Sommer
 
Pycon 2012 What Python can learn from Java
Pycon 2012 What Python can learn from JavaPycon 2012 What Python can learn from Java
Pycon 2012 What Python can learn from Java
jbellis
 
My Valentine Gift - YOU Decide
My Valentine Gift - YOU DecideMy Valentine Gift - YOU Decide
My Valentine Gift - YOU Decide
SizzlynRose
 
Stc 2014 unraveling the mysteries of localization kits
Stc 2014 unraveling the mysteries of localization kitsStc 2014 unraveling the mysteries of localization kits
Stc 2014 unraveling the mysteries of localization kits
David Sommer
 
How to make intelligent web apps
How to make intelligent web appsHow to make intelligent web apps
How to make intelligent web apps
iapain
 
Sample email submission
Sample email submissionSample email submission
Sample email submission
David Sommer
 

Andere mochten auch (20)

Shrunken Head
 Shrunken Head  Shrunken Head
Shrunken Head
 
Linguistic Potluck: Crowdsourcing localization with Rails
Linguistic Potluck: Crowdsourcing localization with RailsLinguistic Potluck: Crowdsourcing localization with Rails
Linguistic Potluck: Crowdsourcing localization with Rails
 
Strategies for Friendly English and Successful Localization
Strategies for Friendly English and Successful LocalizationStrategies for Friendly English and Successful Localization
Strategies for Friendly English and Successful Localization
 
Designing for Multiple Mobile Platforms
Designing for Multiple Mobile PlatformsDesigning for Multiple Mobile Platforms
Designing for Multiple Mobile Platforms
 
Sample of instructions
Sample of instructionsSample of instructions
Sample of instructions
 
Bank Account Of Life
Bank Account Of LifeBank Account Of Life
Bank Account Of Life
 
Open Software Platforms for Mobile Digital Broadcasting
Open Software Platforms for Mobile Digital BroadcastingOpen Software Platforms for Mobile Digital Broadcasting
Open Software Platforms for Mobile Digital Broadcasting
 
mobile development platforms
mobile development platformsmobile development platforms
mobile development platforms
 
Silmeyiniz
SilmeyinizSilmeyiniz
Silmeyiniz
 
My trans kit checklist gw1 ds1_gw3
My trans kit checklist gw1 ds1_gw3My trans kit checklist gw1 ds1_gw3
My trans kit checklist gw1 ds1_gw3
 
Internationalization in Rails 2.2
Internationalization in Rails 2.2Internationalization in Rails 2.2
Internationalization in Rails 2.2
 
Pycon 2012 What Python can learn from Java
Pycon 2012 What Python can learn from JavaPycon 2012 What Python can learn from Java
Pycon 2012 What Python can learn from Java
 
My Valentine Gift - YOU Decide
My Valentine Gift - YOU DecideMy Valentine Gift - YOU Decide
My Valentine Gift - YOU Decide
 
Building Quality Experiences for Users in Any Language
Building Quality Experiences for Users in Any LanguageBuilding Quality Experiences for Users in Any Language
Building Quality Experiences for Users in Any Language
 
Putting Out Fires with Content Strategy (InfoDevDC meetup)
Putting Out Fires with Content Strategy (InfoDevDC meetup)Putting Out Fires with Content Strategy (InfoDevDC meetup)
Putting Out Fires with Content Strategy (InfoDevDC meetup)
 
Stc 2014 unraveling the mysteries of localization kits
Stc 2014 unraveling the mysteries of localization kitsStc 2014 unraveling the mysteries of localization kits
Stc 2014 unraveling the mysteries of localization kits
 
Putting Out Fires with Content Strategy (STC Academic SIG)
Putting Out Fires with Content Strategy (STC Academic SIG)Putting Out Fires with Content Strategy (STC Academic SIG)
Putting Out Fires with Content Strategy (STC Academic SIG)
 
How to make intelligent web apps
How to make intelligent web appsHow to make intelligent web apps
How to make intelligent web apps
 
Sample email submission
Sample email submissionSample email submission
Sample email submission
 
Strategies for Friendly English and Successful Localization (InfoDevWorld 2014)
Strategies for Friendly English and Successful Localization (InfoDevWorld 2014)Strategies for Friendly English and Successful Localization (InfoDevWorld 2014)
Strategies for Friendly English and Successful Localization (InfoDevWorld 2014)
 

Ähnlich wie The ruby on rails i18n core api-Neeraj Kumar

Ähnlich wie The ruby on rails i18n core api-Neeraj Kumar (20)

The Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core ApiThe Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core Api
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
DataMapper
DataMapperDataMapper
DataMapper
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Software Language Design & Engineering
Software Language Design & EngineeringSoftware Language Design & Engineering
Software Language Design & Engineering
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Rails 3 hints
Rails 3 hintsRails 3 hints
Rails 3 hints
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Introducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASHIntroducing Elixir and OTP at the Erlang BASH
Introducing Elixir and OTP at the Erlang BASH
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Elixir formatter Internals
Elixir formatter InternalsElixir formatter Internals
Elixir formatter Internals
 

Mehr von ThoughtWorks

Construction Techniques For Domain Specific Languages
Construction Techniques For Domain Specific LanguagesConstruction Techniques For Domain Specific Languages
Construction Techniques For Domain Specific Languages
ThoughtWorks
 
Ruby 124C41+ - Matz
Ruby 124C41+  - MatzRuby 124C41+  - Matz
Ruby 124C41+ - Matz
ThoughtWorks
 
Glass fish rubyconf-india-2010-Arun gupta
Glass fish rubyconf-india-2010-Arun gupta Glass fish rubyconf-india-2010-Arun gupta
Glass fish rubyconf-india-2010-Arun gupta
ThoughtWorks
 
Aman kingrubyoo pnew
Aman kingrubyoo pnew Aman kingrubyoo pnew
Aman kingrubyoo pnew
ThoughtWorks
 

Mehr von ThoughtWorks (20)

Online and Publishing casestudies
Online and Publishing casestudiesOnline and Publishing casestudies
Online and Publishing casestudies
 
Insurecom Case Study
Insurecom Case StudyInsurecom Case Study
Insurecom Case Study
 
Grameen Case Study
Grameen Case StudyGrameen Case Study
Grameen Case Study
 
BFSI Case Sudies
BFSI Case SudiesBFSI Case Sudies
BFSI Case Sudies
 
Construction Techniques For Domain Specific Languages
Construction Techniques For Domain Specific LanguagesConstruction Techniques For Domain Specific Languages
Construction Techniques For Domain Specific Languages
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in Ruby
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in Ruby
 
Lets build-ruby-app-server: Vineet tyagi
Lets build-ruby-app-server: Vineet tyagiLets build-ruby-app-server: Vineet tyagi
Lets build-ruby-app-server: Vineet tyagi
 
Ruby on Rails versus Django - A newbie Web Developer's Perspective -Shreyank...
 Ruby on Rails versus Django - A newbie Web Developer's Perspective -Shreyank... Ruby on Rails versus Django - A newbie Web Developer's Perspective -Shreyank...
Ruby on Rails versus Django - A newbie Web Developer's Perspective -Shreyank...
 
Nick Sieger-Exploring Rails 3 Through Choices
Nick Sieger-Exploring Rails 3 Through Choices Nick Sieger-Exploring Rails 3 Through Choices
Nick Sieger-Exploring Rails 3 Through Choices
 
Present and Future of Programming Languages - ola bini
Present and Future of Programming Languages - ola biniPresent and Future of Programming Languages - ola bini
Present and Future of Programming Languages - ola bini
 
Ruby 124C41+ - Matz
Ruby 124C41+  - MatzRuby 124C41+  - Matz
Ruby 124C41+ - Matz
 
Mac ruby to the max - Brendan G. Lim
Mac ruby to the max - Brendan G. LimMac ruby to the max - Brendan G. Lim
Mac ruby to the max - Brendan G. Lim
 
Project Fedena and Why Ruby on Rails - ArvindArvind G S
Project Fedena and Why Ruby on Rails - ArvindArvind G SProject Fedena and Why Ruby on Rails - ArvindArvind G S
Project Fedena and Why Ruby on Rails - ArvindArvind G S
 
Glass fish rubyconf-india-2010-Arun gupta
Glass fish rubyconf-india-2010-Arun gupta Glass fish rubyconf-india-2010-Arun gupta
Glass fish rubyconf-india-2010-Arun gupta
 
Aman kingrubyoo pnew
Aman kingrubyoo pnew Aman kingrubyoo pnew
Aman kingrubyoo pnew
 
HadoopThe Hadoop Java Software Framework
HadoopThe Hadoop Java Software FrameworkHadoopThe Hadoop Java Software Framework
HadoopThe Hadoop Java Software Framework
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone Development
 
DSL Construction rith Ruby
DSL Construction rith RubyDSL Construction rith Ruby
DSL Construction rith Ruby
 
Cloud Computing
Cloud  ComputingCloud  Computing
Cloud Computing
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

The ruby on rails i18n core api-Neeraj Kumar

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. before_filter :set_locale def set_locale # if params[:locale] is nil then I18n.default_locale will be used I18n.locale = params[:locale] end
  • 10.
  • 11. # app/controllers/application_controller.rb def default_url_options(options = {}) logger.debug “default_url_options is passed options: #{options.inspect}n” {:locale => I18n.locale} end
  • 12. # config/routes.rb map.resources :books, :path_prefix => '/:locale' # => www.example.com/nl/books map.root '/:locale', :controller => “dashboard”
  • 13.
  • 14.
  • 15. before_filter :set_locale def set_locale I18n.locale = extract_locale_from_uri end
  • 16. def extract_locale_from_tld parsed_locale = request.host.split('.').last I18n.available_locales.include? (parsed_locale.to_sym) ? parsed_locale : nil end
  • 17.
  • 18. def set_locale logger.debug = “* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}” I18n.locale = extract_locale_from_accept_language_header end
  • 19. def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z] {2}/).first end
  • 20. en: activerecord: models: user: foo admin: bar attributes: user: login: “Handle” # => will translate User attribute “login” as “Handle”
  • 21. en: activerecord: errors: messages: blank: “can not has nottin” # => u = User.new # => #<User id:nil, etc> # => u.valid? # => false # => u.errors.on(:name) # => “can not has nottin”
  • 22.
  • 23. en: activerecord: errors: messages: already_registered: “u already is {{model}}” # => u.errors.on(:email) # => “u already is foo”
  • 24. en: activerecord: errors: template: header: one: “1 error prohibted this {{model}} from being saved” other: “{{count}} errors prohibted this {{model}} from being saved” body: “There were problems with the following fields:”
  • 25. i18n i18n i18n backend backend core_ext helpers locales exceptions gettext gettext helpers tag fallbacks locale version
  • 26. backend Interpolation fast simple active_record active_record compiler Interpolation gettext base compiler missing Interpolation helpers cache compiler store_procs Interpolation Interpolation cascader compiler compiler Interpolation links translation chain compiler Interpolation metadata cldr compiler Interpolation pluralization fallbacks compiler
  • 27. def default_locale(locale) @@default_locale = locale.to_sym rescue nil end
  • 28. def backend @@backend ||= Backend::Simple.new end
  • 29. module I18n module Backend class Simple include Base end end end
  • 30. def available_locales @@available_locales ||= backend.available_locales end
  • 31.
  • 32.
  • 33. def default_exception_handler(exception, locale, key, options) return exception.message if MissingTranslationData === exception raise exception end
  • 34.
  • 35. def config Thread.current[:i18n_config] ||= I18n::Config.new end
  • 36.
  • 37. I18n.t :invalid, :scope => [:active_record, :error_messages] # => I18n.translation :invalid :active_record.error_messa ges.invalid
  • 38. I18n.t :foo, :bar => 'baz' #=> 'foo baz' I18n.t :foo, :count => 1 #=> 'foo' I18n.t :foo, :count => 0 #=> 'foos' I18n.t :foo, :count => 2 #=> 'foos' I18n.t :foo, :default => 'bar'
  • 39. def translate(&args) options = args.pop if args.last.is_a?(Hash) key = args.shift locale = options && options.delete(:locale) || config.locale raises = options && options.delete(:raise) config.backend.translate(locale, key, options || {}) rescue I18n::ArgumentError => exception raise exception if raises handle_exception(exception, locale, key, options) end alias :t :translate
  • 40. def localize(object, options = {}) locale = options.delete(:locale) || config.locale format = options.delete(:format) || :default config.backend.localize(locale, object, format, options) end alias :l :localize
  • 41. def load_translations(*filenames) filenames.each { |filename| load_file(filename) } end
  • 42. def load_file(filename) type = File.extname(filename).tr('.', '').downcase raise UnknownFileType.new(type, filename) unless respond_to?(:”load_#(type)”) data = send(:”load_#(type)”, filename) data.each { |locale, d| merge_translation(locale, d) } end
  • 43. def store_translations(locale, data, options = {}) merge_translations(locale, data, options) end
  • 44. def merge_translations(locale, data, options = {}) locale = locale.to_sym translations[locale] ||= {} separator = options[:separator] || I18n.default_separator data = unwind_keys(data, separator) data = deep_symbolized_keys(data) merger = proc do |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : (v2 || v1) end translations[locale].merge!(data, &merger) end
  • 45. def translate(locale, key, options = {}) raise InvalidLocale.new(locale) unless locale return key.map { |k| translate(locale, k, options) } if key.is_a?(Array) if options.empty? entry = resolve(locale, key, lookup(locale, key), options) raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil?
  • 46. else count, scope, default = options.values_at(:count, :scope, :default) values = options.reject { |name, value| RESERVED_KEYS.include?(name) } entry = lookup(locale, key, scope, options) entry = entry.nil? && default ? default(locale, key, default, options) : resolve(locale, key, entry, options)
  • 47. raise(I18n::MissingTranslationData.new(locale, key, options)) if entry.nil? entry = pluralize(locale, entry, count) if count entry = interpolate(locale, entry, values) if values end entry end
  • 48.
  • 49. case match when '%a' then I18n.t(:"date.abbr_day_names”, :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names”, :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
  • 50. when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour end
  • 51.
  • 52. MissingTranslationData # no translation was found for the requested key InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
  • 53.
  • 55. module I18n def just_raise_that_exception(*args) raise args.first end end I18n.exception_handler = :just_raise_that_exception