belorussian 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ require 'rspec/core/rake_task'
3
+ require 'rubygems/specification'
4
+
5
+ task :default => :spec
6
+ desc "Run specs"
7
+ RSpec::Core::RakeTask.new do |t|
8
+ t.pattern = FileList['spec/**/*_spec.rb']
9
+ t.rspec_opts = %w(-fs --color)
10
+ end
data/TODO ADDED
@@ -0,0 +1,4 @@
1
+ TODO
2
+ ====
3
+ * RDoc
4
+
@@ -0,0 +1,26 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ $: << File.expand_path('../lib', __FILE__)
4
+ require 'belorussian/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{belorussian}
8
+ s.version = Belorussian::VERSION::STRING
9
+
10
+ s.required_rubygems_version = '>= 1.3.5'
11
+ s.authors = ["Yaroslav Markin"]
12
+ s.autorequire = %q{belorussian}
13
+ s.description = %q{Belorussian language support for Ruby and Rails}
14
+ s.email = %q{yaroslav@markin.net}
15
+ s.extra_rdoc_files = ["README.textile", "LICENSE", "CHANGELOG", "TODO"]
16
+ s.files = Dir.glob("{lib,spec}/**/**") + %w(CHANGELOG Gemfile LICENSE Rakefile README.textile belorussian.gemspec TODO)
17
+ s.platform = Gem::Platform::RUBY
18
+ s.homepage = %q{http://github.com/yaroslav/belorussian/}
19
+ s.require_paths = ["lib"]
20
+ s.summary = %q{Belorussian language support for Ruby and Rails}
21
+
22
+ s.add_dependency('i18n', '>= 0.5.0')
23
+
24
+ s.add_development_dependency 'activesupport', '>= 3.0.0'
25
+ s.add_development_dependency 'rspec', '~> 2.7.0'
26
+ end
@@ -0,0 +1,98 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ $KCODE = 'u' if RUBY_VERSION < "1.9"
4
+
5
+ require 'i18n'
6
+
7
+ $:.push File.join(File.dirname(__FILE__), 'belorussian')
8
+ require 'russian_rails'
9
+
10
+ module Belorussian
11
+ extend self
12
+
13
+ autoload :Transliteration, 'transliteration'
14
+
15
+ # Belorussian locale
16
+ LOCALE = :'by'
17
+
18
+ # Belorussian locale
19
+ def locale
20
+ LOCALE
21
+ end
22
+
23
+ # Regexp machers for context-based belorussian month names and day names translation
24
+ LOCALIZE_ABBR_MONTH_NAMES_MATCH = /(%[-\d]?d|%e)(.*)(%b)/
25
+ LOCALIZE_MONTH_NAMES_MATCH = /(%[-\d]?d|%e)(.*)(%B)/
26
+ LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH = /^%a/
27
+ LOCALIZE_STANDALONE_DAY_NAMES_MATCH = /^%A/
28
+
29
+ # Init Belorussian i18n: load all translations shipped with library.
30
+ def init_i18n
31
+ I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
32
+ I18n::Backend::Simple.send(:include, I18n::Backend::Transliterator)
33
+
34
+ I18n.load_path.unshift(*locale_files)
35
+
36
+ I18n.reload!
37
+ end
38
+
39
+ # See I18n::translate
40
+ def translate(key, options = {})
41
+ I18n.translate(key, options.merge({ :locale => LOCALE }))
42
+ end
43
+ alias :t :translate
44
+
45
+ # See I18n::localize
46
+ def localize(object, options = {})
47
+ I18n.localize(object, options.merge({ :locale => LOCALE }))
48
+ end
49
+ alias :l :localize
50
+
51
+ # strftime() proxy with Belorussian localization
52
+ def strftime(object, format = :default)
53
+ localize(object, { :format => format })
54
+ end
55
+
56
+ # Simple pluralization proxy
57
+ #
58
+ # Usage:
59
+ # Belorussian.pluralize(1, "вещь", "вещи", "вещей")
60
+ # Belorussian.pluralize(3.14, "вещь", "вещи", "вещей", "вещи")
61
+ def pluralize(n, *variants)
62
+ raise ArgumentError, "Must have a Numeric as a first parameter" unless n.is_a?(Numeric)
63
+ raise ArgumentError, "Must have at least 3 variants for pluralization" if variants.size < 3
64
+ raise ArgumentError, "Must have at least 4 variants for pluralization" if (variants.size < 4 && n != n.round)
65
+ variants_hash = pluralization_variants_to_hash(*variants)
66
+ I18n.backend.send(:pluralize, LOCALE, variants_hash, n)
67
+ end
68
+ alias :p :pluralize
69
+
70
+ # Transliteration for belorussian language
71
+ #
72
+ # Usage:
73
+ # Belorussian.translit("рубин")
74
+ # Belorussian.transliterate("рубин")
75
+ def transliterate(str)
76
+ Belorussian::Transliteration.transliterate(str)
77
+ end
78
+ alias :translit :transliterate
79
+
80
+ protected
81
+ # Returns all locale files shipped with library
82
+ def locale_files
83
+ Dir[File.join(File.dirname(__FILE__), "belorussian", "locale", "**/*")]
84
+ end
85
+
86
+ # Converts an array of pluralization variants to a Hash that can be used
87
+ # with I18n pluralization.
88
+ def pluralization_variants_to_hash(*variants)
89
+ {
90
+ :one => variants[0],
91
+ :few => variants[1],
92
+ :many => variants[2],
93
+ :other => variants[3]
94
+ }
95
+ end
96
+ end
97
+
98
+ Belorussian.init_i18n
@@ -0,0 +1,118 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ # Заменяет хелпер Rails <tt>select_month</tt> и метод <tt>translated_month_names</tt>
4
+ # для поддержки функционала "отдельностоящих имен месяцев".
5
+ #
6
+ # Теперь можно использовать и полные, и сокращенные название месяцев в двух вариантах -- контекстном
7
+ # (по умолчанию) и отдельностоящем (если в текущем языке есть соответствующие переводы).
8
+ # Теперь хелперы поддерживают ключ <tt>:use_standalone_month_names</tt>, хелпер <tt>select_month</tt>
9
+ # устанавливает его по умолчанию.
10
+ # Отдельностоящие имена месяцев также используютс когда указан ключ <tt>:discard_day</tt>.
11
+ #
12
+ #
13
+ # Replaces Rails <tt>select_month</tt> helper and <tt>translated_month_names</tt> private method to provide
14
+ # "standalone month names" feature.
15
+ #
16
+ # It is now possible to use both abbreviated and full month names in two variants (if current locale provides them).
17
+ # All date helpers support <tt>:use_standalone_month_names</tt> key now, <tt>select_month</tt> helper sets
18
+ # it to true by default.
19
+ # Standalone month names are also used when <tt>:discard_day</tt> key is provided.
20
+ if defined?(ActionView::Helpers::DateTimeSelector)
21
+ module ActionView
22
+ module Helpers
23
+ module DateHelper
24
+ # Returns a select tag with options for each of the months January through December with the current month
25
+ # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
26
+ # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
27
+ # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
28
+ # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
29
+ # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
30
+ # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
31
+ # You can also choose if you want to use i18n standalone month names or default month names -- you can
32
+ # force standalone month names usage by using <tt>:use_standalone_month_names</tt> key.
33
+ # Override the field name using the <tt>:field_name</tt> option, 'month' by default.
34
+ #
35
+ #
36
+ # Также поддерживается ключ <tt>:use_standalone_month_names</tt> для явного указания о необходимости
37
+ # использования отдельностоящих имен месяцев, если текущий язык их поддерживает.
38
+ #
39
+ #
40
+ # ==== Examples
41
+ # # Generates a select field for months that defaults to the current month that
42
+ # # will use keys like "January", "March".
43
+ # select_month(Date.today)
44
+ #
45
+ # # Generates a select field for months that defaults to the current month that
46
+ # # is named "start" rather than "month"
47
+ # select_month(Date.today, :field_name => 'start')
48
+ #
49
+ # # Generates a select field for months that defaults to the current month that
50
+ # # will use keys like "1", "3".
51
+ # select_month(Date.today, :use_month_numbers => true)
52
+ #
53
+ # # Generates a select field for months that defaults to the current month that
54
+ # # will use keys like "1 - January", "3 - March".
55
+ # select_month(Date.today, :add_month_numbers => true)
56
+ #
57
+ # # Generates a select field for months that defaults to the current month that
58
+ # # will use keys like "Jan", "Mar".
59
+ # select_month(Date.today, :use_short_month => true)
60
+ #
61
+ # # Generates a select field for months that defaults to the current month that
62
+ # # will use keys like "Januar", "Marts."
63
+ # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
64
+ #
65
+ def select_month(date, options = {}, html_options = {})
66
+ DateTimeSelector.new(date, options.merge(:use_standalone_month_names => true), html_options).select_month
67
+ end
68
+ end
69
+
70
+ class DateTimeSelector #:nodoc:
71
+ private
72
+ # Returns translated month names
73
+ # => [nil, "January", "February", "March",
74
+ # "April", "May", "June", "July",
75
+ # "August", "September", "October",
76
+ # "November", "December"]
77
+ #
78
+ # If :use_short_month option is set
79
+ # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
80
+ # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
81
+ #
82
+ # Also looks up if <tt>:discard_day</tt> or <tt>:use_standalone_month_names</tt> option is set
83
+ # and uses i18n standalone month names if so.
84
+ #
85
+ #
86
+ # Также в зависимости от использования ключей <tt>:discard_day</tt> или <tt>:use_standalone_month_names</tt>
87
+ # убеждается, есть ли соотвествующие переводы в текущем языке и использует "отдельностоящие" названия
88
+ # месяцев по необходимости
89
+ def translated_month_names
90
+ if @options[:use_short_month]
91
+ if I18n.backend.send(:lookup, I18n.locale, :'date.common_abbr_month_names')
92
+ if (@options[:discard_day] || @options[:use_standalone_month_names])
93
+ key = :'date.standalone_abbr_month_names'
94
+ else
95
+ key = :'date.common_abbr_month_names'
96
+ end
97
+ else
98
+ key = :'date.abbr_month_names'
99
+ end
100
+ else
101
+ if I18n.backend.send(:lookup, I18n.locale, :'date.common_month_names')
102
+ if (@options[:discard_day] || @options[:use_standalone_month_names])
103
+ key = :'date.standalone_month_names'
104
+ else
105
+ key = :'date.common_month_names'
106
+ end
107
+ else
108
+ key = :'date.month_names'
109
+ end
110
+ end
111
+
112
+ I18n.translate(key, :locale => @options[:locale])
113
+ end
114
+
115
+ end
116
+ end
117
+ end
118
+ end # if defined?
@@ -0,0 +1,70 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ if defined?(ActiveModel::Errors)
4
+ module ActiveModel
5
+ class Errors
6
+ # Redefine the ActiveModel::Errors.full_messages method:
7
+ # Returns all the full error messages in an array. 'Base' messages are handled as usual.
8
+ # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^'
9
+ # in which case the attribute name is omitted.
10
+ # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'
11
+ #
12
+ # Переопределяет метод ActiveModel::Errors.full_messages. Сообщения об ошибках для атрибутов
13
+ # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^".
14
+ #
15
+ # Так, например,
16
+ #
17
+ # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение'
18
+ #
19
+ # даст сообщение
20
+ #
21
+ # Accepted terms нужно принять соглашение
22
+ #
23
+ # однако,
24
+ #
25
+ # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение'
26
+ #
27
+ # даст сообщение
28
+ #
29
+ # Нужно принять соглашение
30
+ #
31
+ #
32
+ # Returns all the full error messages in an array.
33
+ #
34
+ # class Company
35
+ # validates_presence_of :name, :address, :email
36
+ # validates_length_of :name, :in => 5..30
37
+ # end
38
+ #
39
+ # company = Company.create(:address => '123 First St.')
40
+ # company.errors.full_messages # =>
41
+ # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
42
+ def full_messages
43
+ full_messages = []
44
+
45
+ each do |attribute, messages|
46
+ messages = Array.wrap(messages)
47
+ next if messages.empty?
48
+
49
+ if attribute == :base
50
+ messages.each {|m| full_messages << m }
51
+ else
52
+ attr_name = attribute.to_s.gsub('.', '_').humanize
53
+ attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
54
+ options = { :attribute => attr_name, :default => "%{attribute} %{message}" }
55
+
56
+ messages.each do |m|
57
+ if m =~ /^\^/
58
+ full_messages << m[1..-1]
59
+ else
60
+ full_messages << I18n.t(:"errors.format", options.merge(:message => m))
61
+ end
62
+ end
63
+ end
64
+ end
65
+
66
+ full_messages
67
+ end
68
+ end
69
+ end
70
+ end # if defined?
@@ -0,0 +1,8 @@
1
+ # Rails hacks
2
+ if defined?(ActiveModel)
3
+ require 'active_model_ext/custom_error_message'
4
+ end
5
+
6
+ if defined?(ActionView::Helpers)
7
+ require 'action_view_ext/helpers/date_helper'
8
+ end
@@ -0,0 +1,212 @@
1
+ by:
2
+ number:
3
+ # Используется в number_with_delimiter()
4
+ # Также является установками по умолчанию для 'currency', 'percentage', 'precision', 'human'
5
+ #
6
+ # Used in number_with_delimiter()
7
+ # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
8
+ format:
9
+ # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
10
+ separator: "."
11
+ # Delimets thousands (e.g. 1,000,000 is a million) (always in groups of three)
12
+ delimiter: " "
13
+ # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
14
+ precision: 3
15
+ significant: false
16
+ strip_insignificant_zeros: false
17
+
18
+ # Used in number_to_currency()
19
+ currency:
20
+ format:
21
+ # Формат отображения валюты и обозначение самой валюты
22
+ #
23
+ #
24
+ format: "%n %u"
25
+ negative_format: "-%n %u"
26
+ unit: "руб."
27
+ # These three are to override number.format and are optional
28
+ separator: "."
29
+ delimiter: " "
30
+ precision: 2
31
+ significant: false
32
+ strip_insignificant_zeros: false
33
+
34
+ # Used in number_to_percentage()
35
+ percentage:
36
+ format:
37
+ # These three are to override number.format and are optional
38
+ # separator:
39
+ delimiter: ""
40
+
41
+ # Used in number_to_precision()
42
+ precision:
43
+ format:
44
+ # These three are to override number.format and are optional
45
+ # separator:
46
+ delimiter: ""
47
+ # precision:
48
+
49
+ # Used in number_to_human_size()
50
+ human:
51
+ format:
52
+ # These three are to override number.format and are optional
53
+ # separator:
54
+ delimiter: ""
55
+ precision: 1
56
+ significant: false
57
+ strip_insignificant_zeros: false
58
+
59
+ # Rails 2.2
60
+ # storage_units: [байт, КБ, МБ, ГБ, ТБ]
61
+
62
+ # Rails 2.3+
63
+ storage_units:
64
+ # Storage units output formatting.
65
+ # %u is the storage unit, %n is the number (default: 2 MB)
66
+ format: "%n %u"
67
+ units:
68
+ byte:
69
+ one: "байт"
70
+ few: "байта"
71
+ many: "байт"
72
+ other: "байта"
73
+ kb: "КБ"
74
+ mb: "МБ"
75
+ gb: "ГБ"
76
+ tb: "ТБ"
77
+
78
+ decimal_units:
79
+ format: "%n %u"
80
+ units:
81
+ unit: ""
82
+ thousand:
83
+ one: "тысяча"
84
+ few: "тысяч"
85
+ many: "тысяч"
86
+ other: "тысяч"
87
+ million:
88
+ one: "миллион"
89
+ few: "миллионов"
90
+ many: "миллионов"
91
+ other: "миллионов"
92
+ billion:
93
+ one: "миллиард"
94
+ few: "миллиардов"
95
+ many: "миллиардов"
96
+ other: "миллиардов"
97
+ trillion:
98
+ one: "триллион"
99
+ few: "триллионов"
100
+ many: "триллионов"
101
+ other: "триллионов"
102
+ quadrillion:
103
+ one: "квадриллион"
104
+ few: "квадриллионов"
105
+ many: "квадриллионов"
106
+ other: "квадриллионов"
107
+
108
+ # Используется в хелперах distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
109
+ #
110
+ #
111
+ # Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
112
+ datetime:
113
+ distance_in_words:
114
+ half_a_minute: "меньше минуты"
115
+ less_than_x_seconds:
116
+ one: "меньше %{count} секунды"
117
+ few: "меньше %{count} секунд"
118
+ many: "меньше %{count} секунд"
119
+ other: "меньше %{count} секунды"
120
+ x_seconds:
121
+ one: "%{count} секунда"
122
+ few: "%{count} секунды"
123
+ many: "%{count} секунд"
124
+ other: "%{count} секунды"
125
+ less_than_x_minutes:
126
+ one: "меньше %{count} минуты"
127
+ few: "меньше %{count} минут"
128
+ many: "меньше %{count} минут"
129
+ other: "меньше %{count} минуты"
130
+ x_minutes:
131
+ one: "%{count} минута"
132
+ few: "%{count} минуты"
133
+ many: "%{count} минут"
134
+ other: "%{count} минуты"
135
+ about_x_hours:
136
+ one: "около %{count} часа"
137
+ few: "около %{count} часов"
138
+ many: "около %{count} часов"
139
+ other: "около %{count} часа"
140
+ x_days:
141
+ one: "%{count} день"
142
+ few: "%{count} дня"
143
+ many: "%{count} дней"
144
+ other: "%{count} дня"
145
+ about_x_months:
146
+ one: "около %{count} месяца"
147
+ few: "около %{count} месяцев"
148
+ many: "около %{count} месяцев"
149
+ other: "около %{count} месяца"
150
+ x_months:
151
+ one: "%{count} месяц"
152
+ few: "%{count} месяца"
153
+ many: "%{count} месяцев"
154
+ other: "%{count} месяца"
155
+ about_x_years:
156
+ one: "около %{count} года"
157
+ few: "около %{count} лет"
158
+ many: "около %{count} лет"
159
+ other: "около %{count} лет"
160
+ over_x_years:
161
+ one: "больше %{count} года"
162
+ few: "больше %{count} лет"
163
+ many: "больше %{count} лет"
164
+ other: "больше %{count} лет"
165
+ almost_x_years:
166
+ one: "почти %{count} год"
167
+ few: "почти %{count} года"
168
+ many: "почти %{count} лет"
169
+ other: "почти %{count} лет"
170
+
171
+ prompts:
172
+ year: "Год"
173
+ month: "Месяц"
174
+ day: "День"
175
+ hour: "Часов"
176
+ minute: "Минут"
177
+ second: "Секунд"
178
+
179
+ # Используется в хелпере error_messages_for
180
+ activerecord:
181
+ errors:
182
+ template:
183
+ # Заголовок сообщения об ошибке
184
+ header:
185
+ one: "%{model}: сохранение не удалось из-за %{count} ошибки"
186
+ few: "%{model}: сохранение не удалось из-за %{count} ошибок"
187
+ many: "%{model}: сохранение не удалось из-за %{count} ошибок"
188
+ other: "%{model}: сохранение не удалось из-за %{count} ошибки"
189
+
190
+ # Первый параграф сообщения об ошибке. Можно использовать макрос %{count}
191
+ #
192
+ #
193
+ # The variable :count is also available
194
+ body: "Проблемы возникли со следующими полями:"
195
+
196
+ support:
197
+ select:
198
+ # default value for :prompt => true in FormOptionsHelper
199
+ prompt: "Выберите: "
200
+
201
+ helpers:
202
+ select:
203
+ # default value for :prompt => true in FormOptionsHelper
204
+ prompt: "Выберите: "
205
+
206
+
207
+ # Default translation keys for submit FormHelper
208
+ submit:
209
+ create: 'Создать %{model}'
210
+ update: 'Сохранить %{model}'
211
+ submit: 'Сохранить %{model}'
212
+