russian 0.2.7 → 0.6.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. data/CHANGELOG +24 -0
  2. data/Gemfile +9 -0
  3. data/LICENSE +1 -1
  4. data/README.textile +136 -139
  5. data/Rakefile +4 -49
  6. data/TODO +0 -6
  7. data/lib/russian.rb +18 -39
  8. data/lib/russian/action_view_ext/helpers/date_helper.rb +15 -9
  9. data/lib/russian/active_model_ext/custom_error_message.rb +70 -0
  10. data/lib/russian/locale/actionview.yml +100 -50
  11. data/lib/russian/locale/activemodel.yml +50 -0
  12. data/lib/russian/locale/activerecord.yml +24 -24
  13. data/lib/russian/locale/datetime.rb +39 -0
  14. data/lib/russian/locale/datetime.yml +9 -5
  15. data/lib/russian/locale/pluralization.rb +28 -0
  16. data/lib/russian/locale/transliterator.rb +17 -0
  17. data/lib/russian/russian_rails.rb +8 -0
  18. data/lib/russian/version.rb +9 -0
  19. data/russian.gemspec +26 -0
  20. data/spec/locale_spec.rb +5 -87
  21. data/spec/russian_spec.rb +5 -23
  22. metadata +70 -69
  23. data/init.rb +0 -3
  24. data/lib/russian/active_record_ext/custom_error_message.rb +0 -163
  25. data/lib/russian/active_support_ext/parameterize.rb +0 -31
  26. data/lib/russian/backend/advanced.rb +0 -134
  27. data/lib/russian/locale/pluralize.rb +0 -25
  28. data/lib/vendor/i18n/MIT-LICENSE +0 -20
  29. data/lib/vendor/i18n/README.textile +0 -20
  30. data/lib/vendor/i18n/Rakefile +0 -5
  31. data/lib/vendor/i18n/i18n.gemspec +0 -27
  32. data/lib/vendor/i18n/lib/i18n.rb +0 -199
  33. data/lib/vendor/i18n/lib/i18n/backend/simple.rb +0 -214
  34. data/lib/vendor/i18n/lib/i18n/exceptions.rb +0 -53
  35. data/lib/vendor/i18n/test/all.rb +0 -5
  36. data/lib/vendor/i18n/test/i18n_exceptions_test.rb +0 -100
  37. data/lib/vendor/i18n/test/i18n_test.rb +0 -125
  38. data/lib/vendor/i18n/test/locale/en.rb +0 -1
  39. data/lib/vendor/i18n/test/locale/en.yml +0 -3
  40. data/lib/vendor/i18n/test/simple_backend_test.rb +0 -568
  41. data/lib/vendor/i18n_label/README.textile +0 -38
  42. data/lib/vendor/i18n_label/Rakefile +0 -11
  43. data/lib/vendor/i18n_label/init.rb +0 -1
  44. data/lib/vendor/i18n_label/install.rb +0 -1
  45. data/lib/vendor/i18n_label/lib/i18n_label.rb +0 -23
  46. data/lib/vendor/i18n_label/spec/i18n_label_spec.rb +0 -20
  47. data/lib/vendor/i18n_label/spec/spec_helper.rb +0 -10
  48. data/lib/vendor/i18n_label/tasks/i18n_label_tasks.rake +0 -4
  49. data/lib/vendor/i18n_label/uninstall.rb +0 -1
data/init.rb DELETED
@@ -1,3 +0,0 @@
1
- # Rails plugin init
2
- require 'russian'
3
-
@@ -1,163 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
-
3
- if defined?(ActiveRecord::Error) # Rails 2.3.4+
4
- module ActiveRecord
5
- class Error
6
- protected
7
- if instance_methods.include?('default_options') # Rails 2.3.5+
8
- # Redefine the ActiveRecord::Error::generate_full_message method:
9
- # Returns all the full error messages in an array. 'Base' messages are handled as usual.
10
- # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^'
11
- # in which case the attribute name is omitted.
12
- # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'
13
- #
14
- #
15
- # Переопределяет метод ActiveRecord::Error::generate_full_message. Сообщения об ошибках для атрибутов
16
- # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^".
17
- #
18
- # Так, например,
19
- #
20
- # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение'
21
- #
22
- # даст сообщение
23
- #
24
- # Accepted terms нужно принять соглашение
25
- #
26
- # однако,
27
- #
28
- # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение'
29
- #
30
- # даст сообщение
31
- #
32
- # Нужно принять соглашение
33
- def generate_full_message(options = {})
34
- keys = [
35
- :"full_messages.#{@message}",
36
- :'full_messages.format',
37
- '{{attribute}} {{message}}'
38
- ]
39
-
40
- if self.message.is_a?(String) && self.message =~ /^\^/
41
- ActiveSupport::Deprecation.warn("Using '^' hack for ActiveRecord error messages has been deprecated. Please use errors.full_messages.format I18n key for formatting")
42
-
43
- options[:full_message] = self.message[1..-1]
44
-
45
- keys = [
46
- :"full_messages.#{@message}",
47
- '{{full_message}}'
48
- ]
49
- else
50
- keys = [
51
- :"full_messages.#{@message}",
52
- :'full_messages.format',
53
- '{{attribute}} {{message}}'
54
- ]
55
- end
56
-
57
- options.merge!(:default => keys, :message => self.message)
58
-
59
- I18n.translate(keys.shift, options)
60
- end
61
- else # Rails 2.3.4
62
- # Redefine the ActiveRecord::Error::generate_full_message method:
63
- # Returns all the full error messages in an array. 'Base' messages are handled as usual.
64
- # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^'
65
- # in which case the attribute name is omitted.
66
- # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'
67
- #
68
- #
69
- # Переопределяет метод ActiveRecord::Error::generate_full_message. Сообщения об ошибках для атрибутов
70
- # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^".
71
- #
72
- # Так, например,
73
- #
74
- # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение'
75
- #
76
- # даст сообщение
77
- #
78
- # Accepted terms нужно принять соглашение
79
- #
80
- # однако,
81
- #
82
- # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение'
83
- #
84
- # даст сообщение
85
- #
86
- # Нужно принять соглашение
87
- def generate_full_message(message, options = {})
88
- options.reverse_merge! :message => self.message,
89
- :model => @base.class.human_name,
90
- :attribute => @base.class.human_attribute_name(attribute.to_s),
91
- :value => value
92
-
93
- key = :"full_messages.#{@message}"
94
- defaults = [:'full_messages.format', '{{attribute}} {{message}}']
95
-
96
- if options[:message].is_a?(String) && options[:message] =~ /^\^/
97
- ActiveSupport::Deprecation.warn("Using '^' hack for ActiveRecord error messages has been deprecated. Please use errors.full_messages.format I18n key for formatting")
98
-
99
- options[:full_message] = options[:message][1..-1]
100
- defaults = [:"full_messages.#{@message}.format", '{{full_message}}']
101
- end
102
-
103
- I18n.t(key, options.merge(:default => defaults, :scope => [:activerecord, :errors]))
104
- end
105
- end
106
- end
107
- end
108
-
109
- else # Rails 2.3.3-
110
- module ActiveRecord
111
- class Errors
112
- # DEPRECATED as of Rails 2.3.4
113
- #
114
- # The following is taken from custom_error_message plugin by David Easley
115
- # (http://rubyforge.org/projects/custom-err-msg/)
116
- #
117
- # Redefine the ActiveRecord::Errors::full_messages method:
118
- # Returns all the full error messages in an array. 'Base' messages are handled as usual.
119
- # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^'
120
- # in which case the attribute name is omitted.
121
- # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'
122
- #
123
- #
124
- # Переопределяет метод ActiveRecord::Errors::full_messages. Сообщения об ошибках для атрибутов
125
- # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^".
126
- #
127
- # Так, например,
128
- #
129
- # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение'
130
- #
131
- # даст сообщение
132
- #
133
- # Accepted terms нужно принять соглашение
134
- #
135
- # однако,
136
- #
137
- # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение'
138
- #
139
- # даст сообщение
140
- #
141
- # Нужно принять соглашение
142
- def full_messages
143
- full_messages = []
144
-
145
- @errors.each_key do |attr|
146
- @errors[attr].each do |msg|
147
- next if msg.nil?
148
-
149
- if attr == "base"
150
- full_messages << msg
151
- elsif msg =~ /^\^/
152
- full_messages << msg[1..-1]
153
- else
154
- full_messages << @base.class.human_attribute_name(attr) + " " + msg
155
- end
156
- end
157
- end
158
-
159
- return full_messages
160
- end
161
- end
162
- end
163
- end
@@ -1,31 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
-
3
- module ActiveSupport
4
- module Inflector
5
- # Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
6
- # Transliterates all russian characters in string first, then passes it to ActiveSupport Inflector.
7
- #
8
- # Заменяет все спецсимволы в строке так, что результат может использоваться как часть "красивого" URL.
9
- # От стандартного ActiveSupport Inflector отличается тем, что сначала производится транслитерация
10
- # букв русского алфавита.
11
- #
12
- # ==== Examples
13
- #
14
- # class Person
15
- # def to_param
16
- # "#{id}-#{name.parameterize}"
17
- # end
18
- # end
19
- #
20
- # @person = Person.find(1)
21
- # # => #<Person id: 1, name: "Дональд Кнут">
22
- #
23
- # <%= link_to(@person.name, person_path %>
24
- # # => <a href="/person/1-donald-knut">Дональд Кнут</a>
25
- def parameterize_with_russian(string, sep = '-')
26
- parameterize_without_russian(Russian::transliterate(string), sep)
27
- end
28
- alias_method :parameterize_without_russian, :parameterize
29
- alias_method :parameterize, :parameterize_with_russian
30
- end
31
- end
@@ -1,134 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
-
3
- module I18n
4
- module Backend
5
- # "Продвинутый" бекэнд для I18n.
6
- #
7
- # Наследует Simple бекэнд и полностью с ним совместим. Добаляет поддержку
8
- # для отдельностоящих/контекстных названий дней недели и месяцев.
9
- # Также позволяет каждому языку использовать собственные правила плюрализации,
10
- # объявленные как Proc (<tt>lambda</tt>).
11
- #
12
- #
13
- # Advanced I18n backend.
14
- #
15
- # Extends Simple backend. Allows usage of "standalone" keys
16
- # for DateTime localization and usage of user-defined Proc (lambda) pluralization
17
- # methods in translation tables.
18
- class Advanced < Simple
19
- LOCALIZE_ABBR_MONTH_NAMES_MATCH = /(%d|%e)(.*)(%b)/
20
- LOCALIZE_MONTH_NAMES_MATCH = /(%d|%e)(.*)(%B)/
21
- LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH = /^%a/
22
- LOCALIZE_STANDALONE_DAY_NAMES_MATCH = /^%A/
23
-
24
- # Acts the same as +strftime+, but returns a localized version of the
25
- # formatted date string. Takes a key from the date/time formats
26
- # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
27
- #
28
- #
29
- # Метод отличается от <tt>localize</tt> в Simple бекэнде поддержкой
30
- # отдельностоящих/контекстных названий дней недели и месяцев.
31
- #
32
- #
33
- # Note that it differs from <tt>localize</tt> in Simple< backend by checking for
34
- # "standalone" month name/day name keys in translation and using them if available.
35
- #
36
- # <tt>options</tt> parameter added for i18n-0.3 compliance.
37
- def localize(locale, object, format = :default, options = nil)
38
- raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
39
-
40
- type = object.respond_to?(:sec) ? 'time' : 'date'
41
- # TODO only translate these if format is a String?
42
- formats = translate(locale, :"#{type}.formats")
43
- format = formats[format.to_sym] if formats && formats[format.to_sym]
44
- # TODO raise exception unless format found?
45
- format = format.to_s.dup
46
-
47
- # TODO only translate these if the format string is actually present
48
- # TODO check which format strings are present, then bulk translate then, then replace them
49
-
50
- if lookup(locale, :"date.standalone_abbr_day_names")
51
- format.gsub!(LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH,
52
- translate(locale, :"date.standalone_abbr_day_names")[object.wday])
53
- end
54
- format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday])
55
-
56
- if lookup(locale, :"date.standalone_day_names")
57
- format.gsub!(LOCALIZE_STANDALONE_DAY_NAMES_MATCH,
58
- translate(locale, :"date.standalone_day_names")[object.wday])
59
- end
60
- format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday])
61
-
62
- if lookup(locale, :"date.standalone_abbr_month_names")
63
- format.gsub!(LOCALIZE_ABBR_MONTH_NAMES_MATCH) do
64
- $1 + $2 + translate(locale, :"date.abbr_month_names")[object.mon]
65
- end
66
- format.gsub!(/%b/, translate(locale, :"date.standalone_abbr_month_names")[object.mon])
67
- else
68
- format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon])
69
- end
70
-
71
- if lookup(locale, :"date.standalone_month_names")
72
- format.gsub!(LOCALIZE_MONTH_NAMES_MATCH) do
73
- $1 + $2 + translate(locale, :"date.month_names")[object.mon]
74
- end
75
- format.gsub!(/%B/, translate(locale, :"date.standalone_month_names")[object.mon])
76
- else
77
- format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon])
78
- end
79
-
80
- format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour
81
- object.strftime(format)
82
- end
83
-
84
- protected
85
- # Использует правила плюрализации из таблицы переводов для языка (если присутствуют),
86
- # иначе использует правило плюрализации по умолчанию (английский язык).
87
- #
88
- # Пример задания правила в таблице переводов:
89
- #
90
- # store_translations :'en', {
91
- # :pluralize => lambda { |n| n == 1 ? :one : :other }
92
- # }
93
- #
94
- # Правило должно возвращать один из символов для таблицы переводов:
95
- # :zero, :one, :two, :few, :many, :other
96
- #
97
- #
98
- # Picks a pluralization rule specified in translation tables for a language or
99
- # uses default pluralization rules.
100
- #
101
- # This is how pluralization rules are defined in translation tables, English
102
- # language for example:
103
- #
104
- # store_translations :'en', {
105
- # :pluralize => lambda { |n| n == 1 ? :one : :other }
106
- # }
107
- #
108
- # Rule must return a symbol to use with pluralization, it must be one of:
109
- # :zero, :one, :two, :few, :many, :other
110
- def pluralize(locale, entry, count)
111
- return entry unless entry.is_a?(Hash) and count
112
-
113
- key = :zero if count == 0 && entry.has_key?(:zero)
114
- locale_pluralize = lookup(locale, :pluralize)
115
- if locale_pluralize && locale_pluralize.respond_to?(:call)
116
- key ||= locale_pluralize.call(count)
117
- else
118
- key ||= default_pluralizer(count)
119
- end
120
- raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
121
-
122
- entry[key]
123
- end
124
-
125
- # Default pluralizer, used if pluralization rule is not defined in translations.
126
- #
127
- # Uses English pluralization rules -- it will pick the first translation if count is not equal to 1
128
- # and the second translation if it is equal to 1.
129
- def default_pluralizer(count)
130
- count == 1 ? :one : :other
131
- end
132
- end
133
- end
134
- end
@@ -1,25 +0,0 @@
1
- # -*- encoding: utf-8 -*-
2
-
3
- {
4
- :'ru' => {
5
- :pluralize => lambda { |n|
6
- # Правило плюрализации для русского языка, взято из CLDR, http://unicode.org/cldr/
7
- #
8
- #
9
- # Russian language pluralization rules, taken from CLDR project, http://unicode.org/cldr/
10
- #
11
- # one -> n mod 10 is 1 and n mod 100 is not 11;
12
- # few -> n mod 10 in 2..4 and n mod 100 not in 12..14;
13
- # many -> n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14;
14
- # other -> everything else
15
- #
16
- # Пример
17
- #
18
- # :one = 1, 21, 31, 41, 51, 61...
19
- # :few = 2-4, 22-24, 32-34...
20
- # :many = 0, 5-20, 25-30, 35-40...
21
- # :other = 1.31, 2.31, 5.31...
22
- n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other
23
- }
24
- }
25
- }
@@ -1,20 +0,0 @@
1
- Copyright (c) 2008 The Ruby I18n team
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining
4
- a copy of this software and associated documentation files (the
5
- "Software"), to deal in the Software without restriction, including
6
- without limitation the rights to use, copy, modify, merge, publish,
7
- distribute, sublicense, and/or sell copies of the Software, and to
8
- permit persons to whom the Software is furnished to do so, subject to
9
- the following conditions:
10
-
11
- The above copyright notice and this permission notice shall be
12
- included in all copies or substantial portions of the Software.
13
-
14
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -1,20 +0,0 @@
1
- h1. Ruby I18n gem
2
-
3
- I18n and localization solution for Ruby.
4
-
5
- For information please refer to http://rails-i18n.org
6
-
7
- h2. Authors
8
-
9
- * "Matt Aimonetti":http://railsontherun.com
10
- * "Sven Fuchs":http://www.artweb-design.de
11
- * "Joshua Harvey":http://www.workingwithrails.com/person/759-joshua-harvey
12
- * "Saimon Moore":http://saimonmoore.net
13
- * "Stephan Soller":http://www.arkanis-development.de
14
-
15
- h2. License
16
-
17
- MIT License. See the included MIT-LICENCE file.
18
-
19
-
20
-
@@ -1,5 +0,0 @@
1
- task :default => [:test]
2
-
3
- task :test do
4
- ruby "test/all.rb"
5
- end
@@ -1,27 +0,0 @@
1
- Gem::Specification.new do |s|
2
- s.name = "i18n"
3
- s.version = "0.1.3"
4
- s.date = "2009-01-09"
5
- s.summary = "Internationalization support for Ruby"
6
- s.email = "rails-i18n@googlegroups.com"
7
- s.homepage = "http://rails-i18n.org"
8
- s.description = "Add Internationalization support to your Ruby application."
9
- s.has_rdoc = false
10
- s.authors = ['Sven Fuchs', 'Joshua Harvey', 'Matt Aimonetti', 'Stephan Soller', 'Saimon Moore']
11
- s.files = [
12
- 'i18n.gemspec',
13
- 'lib/i18n/backend/simple.rb',
14
- 'lib/i18n/exceptions.rb',
15
- 'lib/i18n.rb',
16
- 'MIT-LICENSE',
17
- 'README.textile'
18
- ]
19
- s.test_files = [
20
- 'test/all.rb',
21
- 'test/i18n_exceptions_test.rb',
22
- 'test/i18n_test.rb',
23
- 'test/locale/en.rb',
24
- 'test/locale/en.yml',
25
- 'test/simple_backend_test.rb'
26
- ]
27
- end
@@ -1,199 +0,0 @@
1
- # Authors:: Matt Aimonetti (http://railsontherun.com/),
2
- # Sven Fuchs (http://www.artweb-design.de),
3
- # Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey),
4
- # Saimon Moore (http://saimonmoore.net),
5
- # Stephan Soller (http://www.arkanis-development.de/)
6
- # Copyright:: Copyright (c) 2008 The Ruby i18n Team
7
- # License:: MIT
8
- require 'i18n/backend/simple'
9
- require 'i18n/exceptions'
10
-
11
- module I18n
12
- @@backend = nil
13
- @@load_path = nil
14
- @@default_locale = :'en'
15
- @@exception_handler = :default_exception_handler
16
-
17
- class << self
18
- # Returns the current backend. Defaults to +Backend::Simple+.
19
- def backend
20
- @@backend ||= Backend::Simple.new
21
- end
22
-
23
- # Sets the current backend. Used to set a custom backend.
24
- def backend=(backend)
25
- @@backend = backend
26
- end
27
-
28
- # Returns the current default locale. Defaults to :'en'
29
- def default_locale
30
- @@default_locale
31
- end
32
-
33
- # Sets the current default locale. Used to set a custom default locale.
34
- def default_locale=(locale)
35
- @@default_locale = locale
36
- end
37
-
38
- # Returns the current locale. Defaults to I18n.default_locale.
39
- def locale
40
- Thread.current[:locale] ||= default_locale
41
- end
42
-
43
- # Sets the current locale pseudo-globally, i.e. in the Thread.current hash.
44
- def locale=(locale)
45
- Thread.current[:locale] = locale
46
- end
47
-
48
- # Returns an array of locales for which translations are available
49
- def available_locales
50
- backend.available_locales
51
- end
52
-
53
- # Sets the exception handler.
54
- def exception_handler=(exception_handler)
55
- @@exception_handler = exception_handler
56
- end
57
-
58
- # Allow clients to register paths providing translation data sources. The
59
- # backend defines acceptable sources.
60
- #
61
- # E.g. the provided SimpleBackend accepts a list of paths to translation
62
- # files which are either named *.rb and contain plain Ruby Hashes or are
63
- # named *.yml and contain YAML data. So for the SimpleBackend clients may
64
- # register translation files like this:
65
- # I18n.load_path << 'path/to/locale/en.yml'
66
- def load_path
67
- @@load_path ||= []
68
- end
69
-
70
- # Sets the load path instance. Custom implementations are expected to
71
- # behave like a Ruby Array.
72
- def load_path=(load_path)
73
- @@load_path = load_path
74
- end
75
-
76
- # Tells the backend to reload translations. Used in situations like the
77
- # Rails development environment. Backends can implement whatever strategy
78
- # is useful.
79
- def reload!
80
- backend.reload!
81
- end
82
-
83
- # Translates, pluralizes and interpolates a given key using a given locale,
84
- # scope, and default, as well as interpolation values.
85
- #
86
- # *LOOKUP*
87
- #
88
- # Translation data is organized as a nested hash using the upper-level keys
89
- # as namespaces. <em>E.g.</em>, ActionView ships with the translation:
90
- # <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
91
- #
92
- # Translations can be looked up at any level of this hash using the key argument
93
- # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
94
- # returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
95
- #
96
- # Key can be either a single key or a dot-separated key (both Strings and Symbols
97
- # work). <em>E.g.</em>, the short format can be looked up using both:
98
- # I18n.t 'date.formats.short'
99
- # I18n.t :'date.formats.short'
100
- #
101
- # Scope can be either a single key, a dot-separated key or an array of keys
102
- # or dot-separated keys. Keys and scopes can be combined freely. So these
103
- # examples will all look up the same short date format:
104
- # I18n.t 'date.formats.short'
105
- # I18n.t 'formats.short', :scope => 'date'
106
- # I18n.t 'short', :scope => 'date.formats'
107
- # I18n.t 'short', :scope => %w(date formats)
108
- #
109
- # *INTERPOLATION*
110
- #
111
- # Translations can contain interpolation variables which will be replaced by
112
- # values passed to #translate as part of the options hash, with the keys matching
113
- # the interpolation variable names.
114
- #
115
- # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option
116
- # value for the key +bar+ will be interpolated into the translation:
117
- # I18n.t :foo, :bar => 'baz' # => 'foo baz'
118
- #
119
- # *PLURALIZATION*
120
- #
121
- # Translation data can contain pluralized translations. Pluralized translations
122
- # are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
123
- #
124
- # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
125
- # pluralization rules. Other algorithms can be supported by custom backends.
126
- #
127
- # This returns the singular version of a pluralized translation:
128
- # I18n.t :foo, :count => 1 # => 'Foo'
129
- #
130
- # These both return the plural version of a pluralized translation:
131
- # I18n.t :foo, :count => 0 # => 'Foos'
132
- # I18n.t :foo, :count => 2 # => 'Foos'
133
- #
134
- # The <tt>:count</tt> option can be used both for pluralization and interpolation.
135
- # <em>E.g.</em>, with the translation
136
- # <tt>:foo => ['{{count}} foo', '{{count}} foos']</tt>, count will
137
- # be interpolated to the pluralized translation:
138
- # I18n.t :foo, :count => 1 # => '1 foo'
139
- #
140
- # *DEFAULTS*
141
- #
142
- # This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
143
- # I18n.t :foo, :default => 'default'
144
- #
145
- # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
146
- # translation for <tt>:foo</tt> was found:
147
- # I18n.t :foo, :default => :bar
148
- #
149
- # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
150
- # or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
151
- # I18n.t :foo, :default => [:bar, 'default']
152
- #
153
- # <b>BULK LOOKUP</b>
154
- #
155
- # This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
156
- # I18n.t [:foo, :bar]
157
- #
158
- # Can be used with dot-separated nested keys:
159
- # I18n.t [:'baz.foo', :'baz.bar']
160
- #
161
- # Which is the same as using a scope option:
162
- # I18n.t [:foo, :bar], :scope => :baz
163
- def translate(key, options = {})
164
- locale = options.delete(:locale) || I18n.locale
165
- backend.translate(locale, key, options)
166
- rescue I18n::ArgumentError => e
167
- raise e if options[:raise]
168
- send(@@exception_handler, e, locale, key, options)
169
- end
170
- alias :t :translate
171
-
172
- # Localizes certain objects, such as dates and numbers to local formatting.
173
- def localize(object, options = {})
174
- locale = options[:locale] || I18n.locale
175
- format = options[:format] || :default
176
- backend.localize(locale, object, format)
177
- end
178
- alias :l :localize
179
-
180
- protected
181
- # Handles exceptions raised in the backend. All exceptions except for
182
- # MissingTranslationData exceptions are re-raised. When a MissingTranslationData
183
- # was caught and the option :raise is not set the handler returns an error
184
- # message string containing the key/scope.
185
- def default_exception_handler(exception, locale, key, options)
186
- return exception.message if MissingTranslationData === exception
187
- raise exception
188
- end
189
-
190
- # Merges the given locale, key and scope into a single array of keys.
191
- # Splits keys that contain dots into multiple keys. Makes sure all
192
- # keys are Symbols.
193
- def normalize_translation_keys(locale, key, scope)
194
- keys = [locale] + Array(scope) + [key]
195
- keys = keys.map { |k| k.to_s.split(/\./) }
196
- keys.flatten.map { |k| k.to_sym }
197
- end
198
- end
199
- end