rutils 0.2.4 → 0.2.5
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/History.txt +11 -1
- data/Manifest.txt +8 -0
- data/README.txt +8 -3
- data/Rakefile.rb +11 -0
- data/TODO.txt +3 -4
- data/init.rb +6 -3
- data/lib/datetime/datetime.rb +6 -7
- data/lib/integration/integration.rb +0 -21
- data/lib/integration/rails_date_helper_override.rb +30 -4
- data/lib/integration/rails_pre_filter.rb +3 -0
- data/lib/integration/red_cloth_four.rb +24 -0
- data/lib/integration/red_cloth_override.rb +4 -24
- data/lib/integration/red_cloth_three.rb +25 -0
- data/lib/pluralizer/pluralizer.rb +23 -3
- data/lib/rutils.rb +28 -1
- data/test/t_datetime.rb +123 -34
- data/test/t_integration.rb +19 -142
- data/test/t_pluralize.rb +14 -2
- data/test/t_transliteration.rb +8 -8
- data/test/test_integration_bluecloth.rb +17 -0
- data/test/test_integration_redcloth3.rb +31 -0
- data/test/test_integration_redcloth4.rb +31 -0
- data/test/test_rails_filter.rb +27 -0
- data/test/test_rails_helpers.rb +73 -0
- metadata +10 -2
data/History.txt
CHANGED
@@ -1,3 +1,13 @@
|
|
1
|
+
=== 0.2.5 - 08.08.2008
|
2
|
+
* Поддержка Rails Edge (pre-2.2) для хелперов DateTime. RuTils при overrides_enabled пытается поставить себя выше I18n -- при overrides_enabled I18n не вызывается для datetime хелперов. (Yaroslav Markin)
|
3
|
+
* Частичная поддержка RedCloth 4 (julik)
|
4
|
+
* Фильтр для контроллера чтобы установить верный флаг для экшена, то что происходит в экшене - thread local (julik)
|
5
|
+
* Разделяем тесты и хаки (julik)
|
6
|
+
* Добавлена поддержка strftime макроса %e (номер дня в месяце без лидирующего нуля) -- по аналогии с %d, при использовании %e мы склоняем имя месяца (Yaroslav Markin)
|
7
|
+
* Использование с RedCloth 4 больше не вызывает ошибки (совместимости для перегрузки все еще нет) (Yaroslav Markin)
|
8
|
+
* Добавлен метод Fixnum#kopeek для вывода целочисленных Денег (julik)
|
9
|
+
* RuTils::overrides безопасен для нитей (julik)
|
10
|
+
|
1
11
|
=== 0.2.4 - 10.07.2008
|
2
12
|
|
3
13
|
* Форматтер даты-времени должен гарантированно возвращать результат (Eugene Pimenov + julik)
|
@@ -12,7 +22,7 @@
|
|
12
22
|
* Переписаны Date хелперы для Rails. Теперь поддерживаются все опции Rails 1.2--2.0 и
|
13
23
|
Rails 2.1+ (Yaroslav Markin)
|
14
24
|
* Переписаны и дополнены тесты на перегрузку Date хелперов Rails (Yaroslav Markin)
|
15
|
-
* Для тестирования оверрайдов Rails используется gem
|
25
|
+
* Для тестирования оверрайдов Rails используется gem multi_rails
|
16
26
|
* До свидания, <nobr>. Указывайте .nobr { text-wrap: nowrap } в своих стилевых таблицах.
|
17
27
|
|
18
28
|
=== 0.2.3 - 27.09.2007
|
data/Manifest.txt
CHANGED
@@ -12,7 +12,10 @@ lib/gilenson/gilenson.rb
|
|
12
12
|
lib/integration/blue_cloth_override.rb
|
13
13
|
lib/integration/integration.rb
|
14
14
|
lib/integration/rails_date_helper_override.rb
|
15
|
+
lib/integration/rails_pre_filter.rb
|
16
|
+
lib/integration/red_cloth_four.rb
|
15
17
|
lib/integration/red_cloth_override.rb
|
18
|
+
lib/integration/red_cloth_three.rb
|
16
19
|
lib/pluralizer/pluralizer.rb
|
17
20
|
lib/rutils.rb
|
18
21
|
lib/transliteration/bidi.rb
|
@@ -25,3 +28,8 @@ test/t_integration.rb
|
|
25
28
|
test/t_pluralize.rb
|
26
29
|
test/t_rutils_base.rb
|
27
30
|
test/t_transliteration.rb
|
31
|
+
test/test_integration_bluecloth.rb
|
32
|
+
test/test_integration_redcloth3.rb
|
33
|
+
test/test_integration_redcloth4.rb
|
34
|
+
test/test_rails_filter.rb
|
35
|
+
test/test_rails_helpers.rb
|
data/README.txt
CHANGED
@@ -6,11 +6,11 @@ RuTils - простой обработчик русского текста на
|
|
6
6
|
|
7
7
|
== Чье это
|
8
8
|
|
9
|
+
Разработчики RuTils - Julik[http://julik.nl], Mash[http://imfo.ru], {Yaroslav Markin}[http://markin.net/]
|
10
|
+
|
9
11
|
Большое спасибо Роману Иванову aka Kukutz и Николаю Яремко aka Kuso Mendokuzee за
|
10
12
|
реализацию большинства алгоритмов на PHP.
|
11
13
|
|
12
|
-
Разработчики RuTils - Julik[http://julik.nl], Mash[http://imfo.ru], {Yaroslav Markin}[http://markin.net/]
|
13
|
-
|
14
14
|
= Как воспользоваться
|
15
15
|
|
16
16
|
Просто включите rutils в свою программу как библиотеку
|
@@ -44,6 +44,11 @@ RuTils реализует сумму прописью для целых и др
|
|
44
44
|
1.rubl => "один рубль"
|
45
45
|
22.rublja => "двадцать два рубля"
|
46
46
|
|
47
|
+
Если вы храните денежные единицы в целочисленных типах, пользуйтесь "копеечными" вариантами:
|
48
|
+
|
49
|
+
300.kopeek => "три рубля"
|
50
|
+
121.kopeika => "один рубль двадцать одна копейка"
|
51
|
+
|
47
52
|
== Транслит
|
48
53
|
|
49
54
|
RuTils на данный момент реализует простейший транслит "в одну сторону" и
|
@@ -108,7 +113,7 @@ Unicode-тексты в среде UNIX пользуясь стандартны
|
|
108
113
|
Пример использования:
|
109
114
|
|
110
115
|
require 'date' date = Date.new(2005, 11, 9)
|
111
|
-
puts "#{Date::RU_ABBR_MONTHNAMES[date.mon]}" => Ноя
|
116
|
+
puts "#{Date::RU_ABBR_MONTHNAMES[date.mon]}" => Ноя
|
112
117
|
puts "#{Date::RU_MONTHNAMES[date.mon]}" => Ноябрь
|
113
118
|
puts "#{Date::RU_ABBR_DAYNAMES[date.wday]}" => Ср
|
114
119
|
puts "#{Date::RU_DAYNAMES[date.wday]}" => Среда
|
data/Rakefile.rb
CHANGED
@@ -1,8 +1,11 @@
|
|
1
1
|
$KCODE = 'u'
|
2
|
+
$:.reject! { |e| e.include? 'TextMate' }
|
2
3
|
|
3
4
|
require 'lib/rutils'
|
4
5
|
require 'rubygems'
|
5
6
|
|
7
|
+
|
8
|
+
|
6
9
|
begin
|
7
10
|
require 'hoe'
|
8
11
|
|
@@ -10,6 +13,13 @@ begin
|
|
10
13
|
Hoe::RUBY_FLAGS.replace ENV['RUBY_FLAGS'] || "-I#{%w(lib test).join(File::PATH_SEPARATOR)}" +
|
11
14
|
(Hoe::RUBY_DEBUG ? " #{RUBY_DEBUG}" : '')
|
12
15
|
|
16
|
+
# The generic URI syntax mandates that new URI schemes that provide for the
|
17
|
+
# representation of character data in a URI must, in effect, represent characters from
|
18
|
+
# the unreserved set without translation, and should convert all other characters to
|
19
|
+
# bytes according to UTF-8, # and then percent-encode those values. This requirement was
|
20
|
+
# introduced in January 2005 with the publication of RFC 3986. URI schemes # introduced
|
21
|
+
# before this date are not affected.
|
22
|
+
|
13
23
|
# Hoe minus dependency pollution plus unidocs plus rdoc fix. Kommunizm, perestroika.
|
14
24
|
class KolkHoe < Hoe
|
15
25
|
DOCOPTS = %w(--webcvs=http://rutils.rubyforge.org/svn/trunk/%s --charset=utf-8 --promiscuous)
|
@@ -32,6 +42,7 @@ begin
|
|
32
42
|
p.summary = 'Simple processing of russian strings'
|
33
43
|
p.url = "http://rutils.rubyforge.org"
|
34
44
|
p.test_globs = 'test/t_*.rb'
|
45
|
+
p.remote_rdoc_dir = ''
|
35
46
|
p.need_zip = true
|
36
47
|
p.remote_rdoc_dir = ''
|
37
48
|
end
|
data/TODO.txt
CHANGED
@@ -1,8 +1,7 @@
|
|
1
1
|
=TODO
|
2
2
|
|
3
|
-
==Pluralization
|
4
|
-
|
5
|
-
* Истинная плюрализация без передачи рода и вариантов (как в Rails)
|
6
|
-
|
7
3
|
==Rails
|
8
4
|
|
5
|
+
* i18n was merged into Rails trunk (http://github.com/svenfuchs/i18n/tree/master), (http://github.com/svenfuchs/rails/tree/i18n-merge), нужно
|
6
|
+
написать i18n файлы для common stuff (datetime) и Rails.
|
7
|
+
|
data/init.rb
CHANGED
@@ -1,6 +1,9 @@
|
|
1
1
|
=begin
|
2
|
-
Этот файл - заглушка для Rails-плагина.
|
3
|
-
|
2
|
+
Этот файл - заглушка для Rails-плагина.
|
3
|
+
Если поместить rutils/ в папку vendor/plugins/ вашего Rails-приложения,
|
4
|
+
RuTils будет автоматически загружен с включенным флагом <tt>RuTils::overrides = true</tt>.
|
5
|
+
В ActionController::Base будет установлен пре-фильтр устанавливающий флаг <tt>overrides.</tt>
|
4
6
|
=end
|
5
7
|
require File.join(File.dirname(__FILE__), 'lib', 'rutils')
|
6
|
-
RuTils::overrides = true
|
8
|
+
RuTils::overrides = true
|
9
|
+
require File.dirname(__FILE__) + '/lib/integration/rails_pre_filter'
|
data/lib/datetime/datetime.rb
CHANGED
@@ -3,7 +3,7 @@ module RuTils
|
|
3
3
|
|
4
4
|
def self.distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, absolute = false) #nodoc
|
5
5
|
from_time = from_time.to_time if from_time.respond_to?(:to_time)
|
6
|
-
to_time
|
6
|
+
to_time = to_time.to_time if to_time.respond_to?(:to_time)
|
7
7
|
distance_in_minutes = (((to_time - from_time).abs)/60).round
|
8
8
|
distance_in_seconds = ((to_time - from_time).abs).round
|
9
9
|
|
@@ -13,14 +13,14 @@ module RuTils
|
|
13
13
|
|
14
14
|
case distance_in_seconds
|
15
15
|
when 0..5 then 'менее 5 секунд'
|
16
|
-
when 6..10
|
16
|
+
when 6..10 then 'менее 10 секунд'
|
17
17
|
when 11..20 then 'менее 20 секунд'
|
18
18
|
when 21..40 then 'пол-минуты'
|
19
19
|
when 41..59 then 'меньше минуты'
|
20
|
-
else
|
20
|
+
else '1 минуту'
|
21
21
|
end
|
22
22
|
|
23
|
-
when 2..45
|
23
|
+
when 2..45 then distance_in_minutes.to_s +
|
24
24
|
" " + distance_in_minutes.items("минута", "минуты", "минут")
|
25
25
|
when 46..90 then 'около часа'
|
26
26
|
# исключение, сдвигаем на один влево чтобы соответствовать падежу
|
@@ -33,11 +33,12 @@ module RuTils
|
|
33
33
|
end
|
34
34
|
|
35
35
|
def self.ru_strftime(time, format_str='%d.%m.%Y')
|
36
|
-
clean_fmt = format_str.gsub(/%{2}/, RuTils::SUBSTITUTION_MARKER).
|
36
|
+
clean_fmt = format_str.to_s.gsub(/%{2}/, RuTils::SUBSTITUTION_MARKER).
|
37
37
|
gsub(/%a/, Date::RU_ABBR_DAYNAMES[time.wday]).
|
38
38
|
gsub(/%A/, Date::RU_DAYNAMES[time.wday]).
|
39
39
|
gsub(/%b/, Date::RU_ABBR_MONTHNAMES[time.mon]).
|
40
40
|
gsub(/%d(\s)*%B/, '%02d' % time.day + '\1' + Date::RU_INFLECTED_MONTHNAMES[time.mon]).
|
41
|
+
gsub(/%e(\s)*%B/, '%d' % time.day + '\1' + Date::RU_INFLECTED_MONTHNAMES[time.mon]).
|
41
42
|
gsub(/%B/, Date::RU_MONTHNAMES[time.mon]).
|
42
43
|
gsub(/#{RuTils::SUBSTITUTION_MARKER}/, '%%')
|
43
44
|
|
@@ -53,7 +54,6 @@ class Date
|
|
53
54
|
RU_ABBR_MONTHNAMES = [nil] + %w{ янв фев мар апр май июн июл авг сен окт ноя дек }
|
54
55
|
RU_ABBR_DAYNAMES = %w(вск пн вт ср чт пт сб)
|
55
56
|
RU_INFLECTED_MONTHNAMES = [nil] + %w{ января февраля марта апреля мая июня июля августа сентября октября ноября декабря }
|
56
|
-
# RU_DAYNAMES_E -- оставить?
|
57
57
|
RU_DAYNAMES_E = [nil] + %w{первое второе третье четвёртое пятое шестое седьмое восьмое девятое десятое одиннадцатое двенадцатое тринадцатое четырнадцатое пятнадцатое шестнадцатое семнадцатое восемнадцатое девятнадцатое двадцатое двадцать тридцатое тридцатьпервое}
|
58
58
|
end
|
59
59
|
|
@@ -66,7 +66,6 @@ class Time
|
|
66
66
|
end
|
67
67
|
|
68
68
|
class Date
|
69
|
-
|
70
69
|
# Inside rails we have date formatting
|
71
70
|
if self.instance_methods.include?('strftime')
|
72
71
|
alias_method :strftime_norutils, :strftime
|
@@ -1,25 +1,4 @@
|
|
1
1
|
module RuTils
|
2
|
-
@@overrides = true
|
3
|
-
|
4
|
-
# Метод позволяет проверить, включена ли перегрузка функций других модулей.
|
5
|
-
# Попутно он спрашивает модуль Locale (если таковой имеется) является ли русский
|
6
|
-
# текущим языком, и если является, включает перегрузку функций имплицитно.
|
7
|
-
# Это позволяет подчинить настройку перегруженных функций настроенной локали.
|
8
|
-
# Модуль Locale можно получить как часть Ruby-Gettext или как отдельный
|
9
|
-
# модуль ruby-locale. Мы поддерживаем оба.
|
10
|
-
def self.overrides_enabled?
|
11
|
-
if defined?(Locale) and Locale.respond_to?(:current)
|
12
|
-
return true if Locale.current.to_s.split('_').first == 'ru'
|
13
|
-
end
|
14
|
-
@@overrides ? true : false
|
15
|
-
end
|
16
|
-
|
17
|
-
# Включает или выключает перегрузки других модулей. Полезно, например, в случае когда нужно рендерить страницу
|
18
|
-
# сайта на нескольких языках и нужно отключить русское оформление текста для других языков.
|
19
|
-
def self.overrides= (new_override_flag)
|
20
|
-
@@overrides = (new_override_flag ? true : false)
|
21
|
-
end
|
22
|
-
|
23
2
|
# Вновь выполняет перегрузку. Делать это надо после того, как в программу импортированы
|
24
3
|
# другие модули.
|
25
4
|
def self.reload_integrations!
|
@@ -13,6 +13,13 @@ if defined?(Object::ActionView)
|
|
13
13
|
def current; now; end
|
14
14
|
end
|
15
15
|
end
|
16
|
+
|
17
|
+
# В Rails Edge (2.1+) определяется <tt>Date.current</tt> для работы с временными зонами.
|
18
|
+
unless Date.respond_to? :current
|
19
|
+
class << ::Date # :nodoc:
|
20
|
+
def current; now; end
|
21
|
+
end
|
22
|
+
end
|
16
23
|
|
17
24
|
# Заменяет <tt>ActionView::Helpers::DateHelper::distance_of_time_in_words</tt> на русское сообщение.
|
18
25
|
#
|
@@ -29,9 +36,15 @@ if defined?(Object::ActionView)
|
|
29
36
|
# select_month(Date.today, :use_month_numbers => true) # Использует ключи "1", "3"
|
30
37
|
# select_month(Date.today, :add_month_numbers => true) # Использует ключи "1 - Январь", "3 - Март"
|
31
38
|
def select_month(date, options = {}, html_options = {})
|
39
|
+
locale = options[:locale] unless RuTils::overrides_enabled?
|
40
|
+
|
32
41
|
val = date ? (date.kind_of?(Fixnum) ? date : date.month) : ''
|
33
42
|
if options[:use_hidden]
|
34
|
-
|
43
|
+
if self.class.private_instance_methods.include? "_date_hidden_html"
|
44
|
+
_date_hidden_html(options[:field_name] || 'month', val, options)
|
45
|
+
else
|
46
|
+
hidden_html(options[:field_name] || 'month', val, options)
|
47
|
+
end
|
35
48
|
else
|
36
49
|
month_options = []
|
37
50
|
if RuTils::overrides_enabled?
|
@@ -45,9 +58,17 @@ if defined?(Object::ActionView)
|
|
45
58
|
Date::RU_MONTHNAMES
|
46
59
|
end
|
47
60
|
else
|
48
|
-
|
61
|
+
if defined? I18n
|
62
|
+
month_names = options[:use_month_names] || begin
|
63
|
+
key = options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
|
64
|
+
I18n.translate key, :locale => locale
|
65
|
+
end
|
66
|
+
else
|
67
|
+
month_names = options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES
|
68
|
+
end
|
49
69
|
end
|
50
70
|
month_names.unshift(nil) if month_names.size < 13
|
71
|
+
|
51
72
|
1.upto(12) do |month_number|
|
52
73
|
month_name = if options[:use_month_numbers]
|
53
74
|
month_number
|
@@ -63,8 +84,13 @@ if defined?(Object::ActionView)
|
|
63
84
|
)
|
64
85
|
month_options << "\n"
|
65
86
|
end
|
87
|
+
|
66
88
|
if DATE_HELPERS_RECEIVE_HTML_OPTIONS
|
67
|
-
|
89
|
+
if self.class.private_instance_methods.include? "_date_select_html"
|
90
|
+
_date_select_html(options[:field_name] || 'month', month_options.join, options, html_options)
|
91
|
+
else
|
92
|
+
select_html(options[:field_name] || 'month', month_options.join, options, html_options)
|
93
|
+
end
|
68
94
|
else
|
69
95
|
select_html(options[:field_name] || 'month', month_options.join, options)
|
70
96
|
end
|
@@ -73,7 +99,7 @@ if defined?(Object::ActionView)
|
|
73
99
|
|
74
100
|
alias :stock_select_date :select_date
|
75
101
|
# Заменяет ActionView::Helpers::DateHelper::select_date меню выбора русской даты.
|
76
|
-
def select_date(date = Date.
|
102
|
+
def select_date(date = Date.current, options = {}, html_options = {})
|
77
103
|
options[:order] ||= [:day, :month, :year]
|
78
104
|
if DATE_HELPERS_RECEIVE_HTML_OPTIONS
|
79
105
|
stock_select_date(date, options, html_options)
|
@@ -0,0 +1,24 @@
|
|
1
|
+
# RedCloth 4
|
2
|
+
class RedCloth::TextileDoc < String
|
3
|
+
alias_method :to_html_without_rutils, :to_html
|
4
|
+
|
5
|
+
def to_html
|
6
|
+
if RuTils::overrides_enabled?
|
7
|
+
suspended = to_html_without_rutils
|
8
|
+
|
9
|
+
# Return quotes to original state
|
10
|
+
[187, 171, 8220, 8221].map do |e|
|
11
|
+
suspended.gsub! /&\##{e};/, '"'
|
12
|
+
end
|
13
|
+
|
14
|
+
# Return spaces to original state
|
15
|
+
[160].map do |e|
|
16
|
+
suspended.gsub! /&\##{e};/, ' '
|
17
|
+
end
|
18
|
+
|
19
|
+
suspended.gilensize
|
20
|
+
else
|
21
|
+
to_html_without_rutils
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
@@ -1,27 +1,7 @@
|
|
1
1
|
if defined?(Object::RedCloth) && !RedCloth.instance_methods.include?(:htmlesc_without_rutils)
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
alias_method :htmlesc_without_rutils, :htmlesc
|
7
|
-
def htmlesc(text, mode=0) #:nodoc:
|
8
|
-
RuTils::overrides_enabled? ? text : htmlesc_without_rutils(text, mode)
|
9
|
-
end
|
10
|
-
|
11
|
-
# А этот метод обрабатывает Textile Glyphs - ту самую типографицу.
|
12
|
-
# Вместо того чтобы влезать в чужие таблицы мы просто заменим Textile Glyphs на Gilenson - и все будут рады.
|
13
|
-
alias_method :pgl_without_rutils, :pgl
|
14
|
-
def pgl(text) #:nodoc:
|
15
|
-
if RuTils::overrides_enabled?
|
16
|
-
# Suspend the spaces in the start and end of the block because Gilenson chews them off, and RedCloth feeds them to us in packs
|
17
|
-
# that appear between tag starts/stops. We mess up the formatting but preserve the spacing.
|
18
|
-
spaces = Array.new(2,'')
|
19
|
-
text.gsub!(/\A([\s]+)/) { spaces[0] = $1; '' }
|
20
|
-
text.gsub!(/(\s+)\Z/) { spaces[1] = $1; '' }
|
21
|
-
text.replace(spaces[0].to_s + RuTils::Gilenson::Formatter.new(text).to_html + spaces[1].to_s)
|
22
|
-
else
|
23
|
-
pgl_without_rutils(text)
|
24
|
-
end
|
25
|
-
end
|
2
|
+
if RedCloth.class == Module
|
3
|
+
require File.dirname(__FILE__) + '/red_cloth_four'
|
4
|
+
else
|
5
|
+
require File.dirname(__FILE__) + '/red_cloth_three'
|
26
6
|
end
|
27
7
|
end
|
@@ -0,0 +1,25 @@
|
|
1
|
+
# RuTils выполняет перегрузку Textile Glyphs в RedCloth, перенося форматирование спецсимволов на Gilenson.
|
2
|
+
class RedCloth < String #:nodoc:
|
3
|
+
# Этот метод в RedCloth при наличии Гиленсона надо отключать
|
4
|
+
alias_method :htmlesc_without_rutils, :htmlesc
|
5
|
+
def htmlesc(text, mode=0) #:nodoc:
|
6
|
+
RuTils::overrides_enabled? ? text : htmlesc_without_rutils(text, mode)
|
7
|
+
end
|
8
|
+
|
9
|
+
# А этот метод обрабатывает Textile Glyphs - ту самую типографицу.
|
10
|
+
# Вместо того чтобы влезать в чужие таблицы мы просто заменим Textile Glyphs на Gilenson - и все будут рады.
|
11
|
+
alias_method :pgl_without_rutils, :pgl
|
12
|
+
def pgl(text) #:nodoc:
|
13
|
+
if RuTils::overrides_enabled?
|
14
|
+
# Suspend the spaces in the start and end of the block because Gilenson chews them off,
|
15
|
+
# and RedCloth feeds them to us in packs
|
16
|
+
# that appear between tag starts/stops. We mess up the formatting but preserve the spacing.
|
17
|
+
spaces = Array.new(2,'')
|
18
|
+
text.gsub!(/\A([\s]+)/) { spaces[0] = $1; '' }
|
19
|
+
text.gsub!(/(\s+)\Z/) { spaces[1] = $1; '' }
|
20
|
+
text.replace(spaces[0].to_s + RuTils::Gilenson::Formatter.new(text).to_html + spaces[1].to_s)
|
21
|
+
else
|
22
|
+
pgl_without_rutils(text)
|
23
|
+
end
|
24
|
+
end
|
25
|
+
end
|
@@ -5,7 +5,8 @@ module RuTils
|
|
5
5
|
variant = (amount%10==1 && amount%100!=11 ? 1 : amount%10>=2 && amount%10<=4 && (amount%100<10 || amount%100>=20) ? 2 : 3)
|
6
6
|
variants[variant-1]
|
7
7
|
end
|
8
|
-
|
8
|
+
|
9
|
+
# Выводит целое или дробное число как сумму в рублях прописью
|
9
10
|
def self.rublej(amount)
|
10
11
|
pts = []
|
11
12
|
|
@@ -22,6 +23,14 @@ module RuTils
|
|
22
23
|
pts.join(' ')
|
23
24
|
end
|
24
25
|
|
26
|
+
def self.kopeek(amount)
|
27
|
+
pts = []
|
28
|
+
r, k = (amount/100.0).floor, (amount - ((amount/100.0).floor * 100)).to_i
|
29
|
+
pts << RuTils::Pluralization::sum_string(r, 1, "рубль", "рубля", "рублей") unless r.zero?
|
30
|
+
pts << RuTils::Pluralization::sum_string(k, 2, 'копейка', 'копейки', 'копеек') unless k.zero?
|
31
|
+
pts.join(' ')
|
32
|
+
end
|
33
|
+
|
25
34
|
# Выполняет преобразование числа из цифрого вида в символьное
|
26
35
|
# amount - числительное
|
27
36
|
# gender = 1 - мужской, = 2 - женский, = 3 - средний
|
@@ -130,9 +139,9 @@ module RuTils
|
|
130
139
|
end
|
131
140
|
end_word = two_items
|
132
141
|
when 3
|
133
|
-
ones = "три " if end_word = two_items
|
142
|
+
ones = "три " if end_word = two_items # TODO - WTF?
|
134
143
|
when 4
|
135
|
-
ones = "четыре " if end_word = two_items
|
144
|
+
ones = "четыре " if end_word = two_items # TODO - WTF?
|
136
145
|
when 5
|
137
146
|
ones = "пять "
|
138
147
|
when 6
|
@@ -227,6 +236,14 @@ module RuTils
|
|
227
236
|
alias :rubl :rublej
|
228
237
|
alias :rublja :rublej
|
229
238
|
end
|
239
|
+
|
240
|
+
module FixnumFormatting
|
241
|
+
def kopeek
|
242
|
+
RuTils::Pluralization.kopeek(self)
|
243
|
+
end
|
244
|
+
alias :kopeika :kopeek
|
245
|
+
alias :kopeiki :kopeek
|
246
|
+
end
|
230
247
|
end
|
231
248
|
end
|
232
249
|
|
@@ -234,6 +251,9 @@ class Object::Numeric
|
|
234
251
|
include RuTils::Pluralization::NumericFormatting
|
235
252
|
end
|
236
253
|
|
254
|
+
class Object::Fixnum
|
255
|
+
include RuTils::Pluralization::FixnumFormatting
|
256
|
+
end
|
237
257
|
|
238
258
|
class Object::Float
|
239
259
|
include RuTils::Pluralization::FloatFormatting
|
data/lib/rutils.rb
CHANGED
@@ -8,7 +8,7 @@ module RuTils
|
|
8
8
|
INSTALLATION_DIRECTORY = File.expand_path(File.dirname(__FILE__) + '/../') #:nodoc:
|
9
9
|
MAJOR = 0 #:nodoc:
|
10
10
|
MINOR = 2 #:nodoc:
|
11
|
-
TINY =
|
11
|
+
TINY = 5 #:nodoc:
|
12
12
|
|
13
13
|
# Стандартный маркер для подстановок - invalid UTF sequence
|
14
14
|
SUBSTITUTION_MARKER = "\xF0\xF0\xF0\xF0" #:nodoc:
|
@@ -18,6 +18,33 @@ module RuTils
|
|
18
18
|
# Версия RuTils
|
19
19
|
VERSION = [MAJOR, MINOR ,TINY].join('.')
|
20
20
|
|
21
|
+
@@overrides = true
|
22
|
+
|
23
|
+
# Метод позволяет проверить, включена ли перегрузка функций других модулей.
|
24
|
+
# Попутно он спрашивает модуль Locale (если таковой имеется) является ли русский
|
25
|
+
# текущим языком, и если является, включает перегрузку функций имплицитно.
|
26
|
+
# Это позволяет подчинить настройку перегруженных функций настроенной локали.
|
27
|
+
# Модуль Locale можно получить как часть Ruby-Gettext или как отдельный
|
28
|
+
# модуль ruby-locale. Мы поддерживаем оба.
|
29
|
+
def overrides_enabled?
|
30
|
+
if defined?(Locale) and Locale.respond_to?(:current)
|
31
|
+
return true if Locale.current.to_s.split('_').first == 'ru'
|
32
|
+
end
|
33
|
+
thread_local_or_own_flag ? true : false
|
34
|
+
end
|
35
|
+
alias_method :overrides, :overrides_enabled?
|
36
|
+
module_function :overrides_enabled?
|
37
|
+
|
38
|
+
# Включает или выключает перегрузки других модулей. Полезно, например, в случае когда нужно рендерить страницу
|
39
|
+
# сайта на нескольких языках и нужно отключить русское оформление текста для других языков.
|
40
|
+
def overrides=(new_override_flag)
|
41
|
+
Thread.current[:rutils_overrided_enabled] = (new_override_flag ? true : false)
|
42
|
+
end
|
43
|
+
module_function :overrides=
|
44
|
+
|
45
|
+
def self.thread_local_or_own_flag
|
46
|
+
Thread.current.keys.include?(:rutils_overrided_enabled) ? Thread.current[:rutils_overrided_enabled] : false
|
47
|
+
end
|
21
48
|
|
22
49
|
def self.load_component(name) #:nodoc:
|
23
50
|
require File.join(RuTils::INSTALLATION_DIRECTORY, "lib", name.to_s, name.to_s)
|
data/test/t_datetime.rb
CHANGED
@@ -4,54 +4,143 @@ require File.dirname(__FILE__) + '/../lib/rutils'
|
|
4
4
|
|
5
5
|
class DistanceOfTimeTest < Test::Unit::TestCase
|
6
6
|
def test_distance_of_time_in_words
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
7
|
+
assert_format_eq "меньше минуты", 0, 50
|
8
|
+
assert_format_eq "2 минуты", 0, 140
|
9
|
+
assert_format_eq "около 2 часов", 0, 60*114
|
10
|
+
assert_format_eq "около 3 часов", 0, 60*120+60*60
|
11
|
+
assert_format_eq "около 5 часов", 60*60*5
|
12
|
+
end
|
13
|
+
|
14
|
+
def assert_format_eq(str, *from_and_distance)
|
15
|
+
assert_equal str, RuTils::DateTime.distance_of_time_in_words(*from_and_distance)
|
12
16
|
end
|
13
17
|
end
|
14
18
|
|
15
19
|
class StrftimeRuTest < Test::Unit::TestCase
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
RuTils::
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
20
|
+
|
21
|
+
def test_a_formatter_should_actually_return
|
22
|
+
the_fmt = "Это случилось %d %B"
|
23
|
+
assert_equal "Это случилось 01 декабря", RuTils::DateTime::ru_strftime(Time.local(1985, "dec", 01), the_fmt)
|
24
|
+
end
|
25
|
+
|
26
|
+
def test_should_not_touch_double_marks
|
27
|
+
assert_format_eq "%a, %A, %b, %B", Time.local(2005,"dec",31), "%%a, %%A, %%b, %%B",
|
28
|
+
"Should reduce double marks to single marks with no substitutions"
|
29
|
+
end
|
30
|
+
|
31
|
+
def test_should_replace_triple_marks
|
32
|
+
assert_format_eq "%сб, %суббота, %дек, %декабрь", Time.local(2005,"dec",31), "%%%a, %%%A, %%%b, %%%B",
|
33
|
+
"Should reduce triple marks to %formatted"
|
34
|
+
end
|
35
|
+
|
36
|
+
def test_should_replace_shorthands
|
37
|
+
assert_format_eq "сб, суббота, дек, декабрь", Time.local(2005,"dec",31), "%a, %A, %b, %B",
|
38
|
+
"Should replace shorthands"
|
39
|
+
end
|
40
|
+
|
41
|
+
def test_percent_d
|
42
|
+
assert_format_eq "01 декабря", Time.local(1985, "dec", 01), "%d %B",
|
43
|
+
"Should format %d with leading zero and replace month"
|
44
|
+
assert_format_eq "11 декабря", Time.local(1985, "dec", 11), "%d %B",
|
45
|
+
"Should format 11 with leading zero and replace month"
|
46
|
+
end
|
47
|
+
|
48
|
+
def test_percent_e
|
49
|
+
assert_format_eq "1 декабря", Time.local(1985, "dec", 01), "%e %B",
|
50
|
+
"Should format %e w/o leading zero and replace month"
|
51
|
+
assert_format_eq "11 декабря", Time.local(1985, "dec", 11), "%e %B",
|
52
|
+
"Should format 11 w/o leading zero and replace month"
|
53
|
+
end
|
54
|
+
|
55
|
+
def test_all_shorthands
|
56
|
+
assert_format_eq "Сегодня: 31 декабря, суббота, 2005 года", Time.local(2005,"dec",31),
|
57
|
+
"Сегодня: %d %B, %A, %Y года", "Should format with short format string"
|
58
|
+
assert_format_eq "Сегодня: ноябрь, 30 число, дождик в четверг, а год у нас - 2006", Time.local(2006,11,30),
|
59
|
+
"Сегодня: %B, %d число, дождик в %A, а год у нас - %Y", "Should format with long format string"
|
60
|
+
end
|
61
|
+
|
62
|
+
def test_shorthands_defined
|
63
|
+
date = Date.new(2005, 12, 31)
|
64
|
+
assert_equal "дек декабрь сб суббота", "#{Date::RU_ABBR_MONTHNAMES[date.mon]} #{Date::RU_MONTHNAMES[date.mon]} #{Date::RU_ABBR_DAYNAMES[date.wday]} #{Date::RU_DAYNAMES[date.wday]}"
|
32
65
|
|
33
|
-
|
66
|
+
date = Date.new(2005, 11, 9)
|
67
|
+
assert_equal "Nov November Wed Wednesday", "#{Date::ABBR_MONTHNAMES[date.mon]} #{Date::MONTHNAMES[date.mon]} #{Date::ABBR_DAYNAMES[date.wday]} #{Date::DAYNAMES[date.wday]}"
|
68
|
+
|
69
|
+
# We do not support strftime on date at this point
|
70
|
+
# assert_equal "сб, суббота, дек, декабрь", date.strftime("%a, %A, %b, %B")
|
71
|
+
end
|
72
|
+
|
73
|
+
def test_formatter_should_not_mutate_passed_format_strings
|
74
|
+
the_fmt, backup = "Это случилось %d %B", "Это случилось %d %B"
|
75
|
+
assert_equal "Это случилось 01 декабря", RuTils::DateTime::ru_strftime(Time.local(1985, "dec", 01), the_fmt)
|
76
|
+
assert_equal the_fmt, backup
|
77
|
+
end
|
78
|
+
|
79
|
+
def test_formatter_should_downagrade_format_strings_to_string
|
80
|
+
the_fmt, backup = "Это случилось %d %B", "Это случилось %d %B"
|
81
|
+
assert_nothing_raised do
|
82
|
+
assert_format_eq "Это случилось 01 декабря", Time.local(1985, "dec", 01), the_fmt.to_sym
|
83
|
+
end
|
84
|
+
end
|
85
|
+
|
86
|
+
def assert_format_eq(str, time_or_date, fmt, msg = 'Should format as desired')
|
87
|
+
r = RuTils::DateTime::ru_strftime(time_or_date, fmt)
|
88
|
+
assert_not_nil r, "The formatter should have returned a not-nil value for #{time_or_date} and #{fmt}"
|
89
|
+
assert_kind_of String, "The formatter should have returned a String for #{time_or_date} and #{fmt}"
|
90
|
+
assert_equal str, r, msg
|
91
|
+
end
|
92
|
+
end
|
93
|
+
|
94
|
+
class StrftimeTest < Test::Unit::TestCase
|
95
|
+
def test_strftime_bypassed_with_no_overrides
|
96
|
+
with_overrides_set_to(false) do
|
34
97
|
assert_equal "Sat, Saturday, Dec, December", Time.local(2005,"dec",31).strftime("%a, %A, %b, %B")
|
35
98
|
assert_equal "%a, %A, %b, %B", Time.local(2005,"dec",31).strftime("%%a, %%A, %%b, %%B")
|
36
99
|
assert_equal "%Sat, %Saturday, %Dec, %December", Time.local(2005,"dec",31).strftime("%%%a, %%%A, %%%b, %%%B")
|
37
100
|
assert_equal "Сегодня: 31 December, Saturday, 2005 год", Time.local(2005,"dec",31).strftime("Сегодня: %d %B, %A, %Y год")
|
38
101
|
assert_equal "01 December", Time.local(1985, "dec", 01).strftime("%d %B")
|
39
102
|
assert_equal "11 December", Time.local(1985, "dec", 11).strftime("%d %B")
|
40
|
-
|
41
|
-
date = Date.new(2005, 11, 9)
|
42
|
-
assert_equal "Nov November Wed Wednesday", "#{Date::ABBR_MONTHNAMES[date.mon]} #{Date::MONTHNAMES[date.mon]} #{Date::ABBR_DAYNAMES[date.wday]} #{Date::DAYNAMES[date.wday]}"
|
43
|
-
|
44
|
-
RuTils::overrides = @@old_overrides
|
103
|
+
end
|
45
104
|
end
|
46
105
|
|
47
|
-
def
|
48
|
-
|
49
|
-
|
106
|
+
def test_strftime_used_with_overrides
|
107
|
+
with_overrides_set_to(true) do
|
108
|
+
assert_equal "Сегодня: 31 декабря, суббота, 2005 год",
|
109
|
+
Time.local(2005,"dec",31).strftime("Сегодня: %d %B, %A, %Y год")
|
110
|
+
end
|
50
111
|
end
|
51
112
|
|
52
|
-
def
|
53
|
-
|
54
|
-
|
55
|
-
|
113
|
+
def test_overrides_should_be_thread_safe
|
114
|
+
a = Thread.new do
|
115
|
+
120.times do
|
116
|
+
RuTils::overrides = true
|
117
|
+
sleep(rand(10)/200.0)
|
118
|
+
assert_equal "11 декабря", Time.local(1985, "dec", 11).strftime("%d %B")
|
119
|
+
RuTils::overrides = false
|
120
|
+
end
|
121
|
+
end
|
122
|
+
|
123
|
+
b = Thread.new do
|
124
|
+
120.times do
|
125
|
+
RuTils::overrides = false
|
126
|
+
sleep(rand(10)/200.0)
|
127
|
+
assert_equal "11 December", Time.local(1985, "dec", 11).strftime("%d %B")
|
128
|
+
RuTils::overrides = true
|
129
|
+
end
|
130
|
+
end
|
131
|
+
|
132
|
+
ensure
|
133
|
+
a.join; b.join
|
134
|
+
end
|
135
|
+
|
136
|
+
def with_overrides_set_to(value, &blk)
|
137
|
+
begin
|
138
|
+
RuTils::overrides, s = value, RuTils::overrides_enabled?
|
139
|
+
yield
|
140
|
+
ensure;
|
141
|
+
RuTils::overrides = s
|
142
|
+
end
|
56
143
|
end
|
57
144
|
end
|
145
|
+
|
146
|
+
|
data/test/t_integration.rb
CHANGED
@@ -2,29 +2,31 @@ $KCODE = 'u'
|
|
2
2
|
require 'rubygems'
|
3
3
|
require 'test/unit'
|
4
4
|
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
5
|
+
def requiring_with_dependencies(*tests)
|
6
|
+
begin
|
7
|
+
yield
|
8
|
+
tests.map {|t| require File.join(File.dirname(__FILE__), t) }
|
9
|
+
rescue LoadError => e
|
10
|
+
$stderr.puts "Skipping integration test - #{e}"
|
11
|
+
end
|
9
12
|
end
|
10
13
|
|
11
|
-
|
14
|
+
requiring_with_dependencies { require 'multi_rails_init' }
|
15
|
+
|
16
|
+
requiring_with_dependencies('test_rails_helpers', 'test_rails_filter') do
|
12
17
|
require 'action_controller' unless defined?(ActionController)
|
13
18
|
require 'action_view' unless defined?(ActionView)
|
14
|
-
rescue LoadError
|
15
|
-
$skip_rails = true
|
16
19
|
end
|
17
20
|
|
18
|
-
begin
|
19
|
-
require 'RedCloth' unless defined?(RedCloth)
|
20
|
-
rescue LoadError
|
21
|
-
$skip_redcloth = true
|
22
|
-
end
|
23
21
|
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
22
|
+
requiring_with_dependencies('test_integration_bluecloth') { require 'bluecloth' }
|
23
|
+
requiring_with_dependencies do
|
24
|
+
require 'RedCloth' unless defined? RedCloth
|
25
|
+
if RedCloth::VERSION =~ /^3/
|
26
|
+
require File.dirname(__FILE__) + '/test_integration_redcloth3'
|
27
|
+
else
|
28
|
+
require File.dirname(__FILE__) + '/test_integration_redcloth4'
|
29
|
+
end
|
28
30
|
end
|
29
31
|
|
30
32
|
require File.dirname(__FILE__) + '/../lib/rutils'
|
@@ -41,129 +43,4 @@ class IntegrationFlagTest < Test::Unit::TestCase
|
|
41
43
|
RuTils::overrides = true
|
42
44
|
assert RuTils::overrides_enabled?
|
43
45
|
end
|
44
|
-
end
|
45
|
-
|
46
|
-
# Интеграция с RedCloth - Textile.
|
47
|
-
# Нужно иметь в виду что Textile осуществляет свою обработку типографики, которую мы подменяем!
|
48
|
-
class TextileIntegrationTest < Test::Unit::TestCase
|
49
|
-
def test_integration_textile
|
50
|
-
raise "You must have RedCloth to test Textile integration" and return if $skip_redcloth
|
51
|
-
|
52
|
-
RuTils::overrides = true
|
53
|
-
assert RuTils.overrides_enabled?
|
54
|
-
assert_equal "<p>И вот «они пошли туда», и шли шли шли</p>",
|
55
|
-
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
56
|
-
|
57
|
-
RuTils::overrides = false
|
58
|
-
assert !RuTils::overrides_enabled?
|
59
|
-
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
60
|
-
RedCloth.new("*strong text* and _emphasized text_").to_html, "Spaces should be preserved \
|
61
|
-
without RuTils"
|
62
|
-
|
63
|
-
RuTils::overrides = true
|
64
|
-
assert RuTils.overrides_enabled?
|
65
|
-
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
66
|
-
RedCloth.new("*strong text* and _emphasized text_").to_html, "Spaces should be preserved"
|
67
|
-
|
68
|
-
RuTils::overrides = false
|
69
|
-
assert !RuTils.overrides_enabled?
|
70
|
-
assert_equal "<p>И вот “они пошли туда”, и шли шли шли</p>",
|
71
|
-
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
72
|
-
|
73
|
-
end
|
74
|
-
end
|
75
|
-
|
76
|
-
# Интеграция с BlueCloth - Markdown
|
77
|
-
# Сам Markdown никакой обработки типографики не производит (это делает RubyPants, но вряд ли его кто-то юзает на практике)
|
78
|
-
class MarkdownIntegrationTest < Test::Unit::TestCase
|
79
|
-
def test_integration_markdown
|
80
|
-
raise "You must have BlueCloth to test Markdown integration" and return if $skip_bluecloth
|
81
|
-
|
82
|
-
RuTils::overrides = true
|
83
|
-
assert RuTils.overrides_enabled?
|
84
|
-
assert_equal "<p>И вот «они пошли туда», и шли шли шли</p>",
|
85
|
-
BlueCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
86
|
-
|
87
|
-
RuTils::overrides = false
|
88
|
-
assert !RuTils.overrides_enabled?
|
89
|
-
assert_equal "<p>И вот \"они пошли туда\", и шли шли шли</p>",
|
90
|
-
BlueCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
91
|
-
end
|
92
|
-
end
|
93
|
-
|
94
|
-
TEST_DATE = Date.parse("1983-10-15") # coincidentially...
|
95
|
-
TEST_TIME = Time.local(1983, 10, 15, 12, 15) # also coincidentially...
|
96
|
-
|
97
|
-
# Перегрузка helper'ов Rails
|
98
|
-
class RailsHelpersOverrideTest < Test::Unit::TestCase
|
99
|
-
# Вспомогательный класс для тестирования перегруженного DateHelper
|
100
|
-
class HelperStub
|
101
|
-
# для тестирования to_datetime_select_tag
|
102
|
-
def date_field; TEST_TIME; end
|
103
|
-
end
|
104
|
-
|
105
|
-
def setup
|
106
|
-
raise "You must have Rails to test ActionView integration" and return if $skip_rails
|
107
|
-
|
108
|
-
RuTils::overrides = true
|
109
|
-
# А никто и не говорил что класс должен быть один :-)
|
110
|
-
k = Class.new(HelperStub)
|
111
|
-
[ActionView::Helpers::TagHelper, ActionView::Helpers::DateHelper].each{|m| k.send(:include, m)}
|
112
|
-
@stub = k.new
|
113
|
-
end
|
114
|
-
|
115
|
-
def test_distance_of_time_in_words
|
116
|
-
assert_equal "20 минут", @stub.distance_of_time_in_words(Time.now - 20.minutes, Time.now)
|
117
|
-
end
|
118
|
-
|
119
|
-
# TODO - TextMate это не хайлайтит, и это _крайне_ достает
|
120
|
-
def test_select_month
|
121
|
-
assert_match /июль/, @stub.select_month(TEST_DATE),
|
122
|
-
"Месяц в выборе месяца должен быть указан в именительном падеже"
|
123
|
-
assert_match />7\<\/option\>/, @stub.select_month(TEST_DATE, :use_month_numbers => true),
|
124
|
-
"Хелпер select_month с номером месяца вместо названия месяца"
|
125
|
-
assert_match /10\ \-\ октябрь/, @stub.select_month(TEST_DATE, :add_month_numbers => true),
|
126
|
-
"Хелпер select_month с номером и названием месяца"
|
127
|
-
assert_match /\>июн\<\/option\>/, @stub.select_month(TEST_DATE, :use_short_month => true),
|
128
|
-
"Короткое имя месяца при использовании опции :use_short_month"
|
129
|
-
assert_match /name\=\"date\[foobar\]\"/, @stub.select_month(TEST_DATE, :field_name => "foobar"),
|
130
|
-
"Хелпер select_month должен принимать опцию :field_name"
|
131
|
-
assert_match /type\=\"hidden\".+value\=\"10\"/m, @stub.select_month(TEST_DATE, :use_hidden => true),
|
132
|
-
"Хелпер select_month должен принимать опцию :use_hidden"
|
133
|
-
end
|
134
|
-
|
135
|
-
def test_select_date
|
136
|
-
assert_match /date\_day.+date\_month.+date\_year/m, @stub.select_date(TEST_DATE),
|
137
|
-
"Хелпер select_date должен выводить поля в следующем порядке: день, месяц, год"
|
138
|
-
assert_match /декабря/, @stub.select_date(TEST_DATE),
|
139
|
-
"Имя месяца должно быть указано в родительном падеже"
|
140
|
-
assert_match /декабря/, @stub.select_date(TEST_DATE, :order => [:month, :year]),
|
141
|
-
"Хелпер select_date не позволяет опускать фрагменты, имя месяца должно быть указано в родительном падеже"
|
142
|
-
assert_match @stub.select_date, @stub.select_date(Time.now),
|
143
|
-
"Хелпер select_date без параметров работает с текущей датой"
|
144
|
-
end
|
145
|
-
|
146
|
-
def test_select_datetime
|
147
|
-
assert_match /date\_day.+date\_month.+date\_year/m, @stub.select_datetime(TEST_TIME),
|
148
|
-
"Хелпер select_datetime должен выводить поля в следующем порядке: день, месяц, год"
|
149
|
-
end
|
150
|
-
|
151
|
-
def test_html_options
|
152
|
-
if ActionView::Helpers::DateHelper::DATE_HELPERS_RECEIVE_HTML_OPTIONS
|
153
|
-
assert_match /id\=\"foobar\"/m, @stub.select_month(TEST_DATE, {}, :id => "foobar"),
|
154
|
-
"Хелпер select_month принимает html_options"
|
155
|
-
|
156
|
-
assert_match /id\=\"foobar\"/m, @stub.select_date(TEST_DATE, {}, :id => "foobar"),
|
157
|
-
"Хелпер select_date принимает html_options"
|
158
|
-
end
|
159
|
-
end
|
160
|
-
|
161
|
-
def test_instance_tag
|
162
|
-
@it = ActionView::Helpers::InstanceTag.new(:stub, :date_field, self).to_datetime_select_tag
|
163
|
-
assert_match /\>10\<.+\>октября\<.+\>1983\</m, @it,
|
164
|
-
"to_datetime_select_rag должен выводить поля в следующем порядке: день, месяц, год"
|
165
|
-
assert_match /июля/m, @it,
|
166
|
-
"to_datetime_select_tag выводит месяц в родительном падеже"
|
167
|
-
end
|
168
|
-
end
|
169
|
-
|
46
|
+
end
|
data/test/t_pluralize.rb
CHANGED
@@ -34,14 +34,26 @@ class PropisjuTestCase < Test::Unit::TestCase
|
|
34
34
|
assert_equal "колес", 260.items("колесо", "колеса", "колес")
|
35
35
|
end
|
36
36
|
|
37
|
-
def
|
37
|
+
def test_rublej
|
38
38
|
assert_equal "сто двадцать три рубля", 123.rublej
|
39
39
|
assert_equal "триста сорок три рубля двадцать копеек", (343.20).rublej
|
40
40
|
assert_equal "сорок две копейки", (0.4187).rublej
|
41
41
|
assert_equal "триста тридцать два рубля", (331.995).rublej
|
42
42
|
assert_equal "один рубль", 1.rubl
|
43
43
|
assert_equal "три рубля четырнадцать копеек", (3.14).rublja
|
44
|
-
end
|
44
|
+
end
|
45
|
+
|
46
|
+
def test_kopeek
|
47
|
+
assert_equal "сто двадцать три рубля", 12300.kopeek
|
48
|
+
assert_equal "три рубля четырнадцать копеек", 314.kopeek
|
49
|
+
assert_equal "тридцать две копейки", 32.kopeek
|
50
|
+
assert_equal "двадцать одна копейка", 21.kopeika
|
51
|
+
assert_equal "три копейки", 3.kopeiki
|
52
|
+
end
|
53
|
+
|
54
|
+
def test_kopeek_should_not_be_available_on_floats
|
55
|
+
assert_raise(NoMethodError) { (3.3).kopeek }
|
56
|
+
end
|
45
57
|
end
|
46
58
|
|
47
59
|
#class PluralizeTestCase < Test::Unit::TestCase
|
data/test/t_transliteration.rb
CHANGED
@@ -90,20 +90,20 @@ class BiDiTranslitTest < Test::Unit::TestCase
|
|
90
90
|
end
|
91
91
|
|
92
92
|
def test_bidi_translify
|
93
|
-
@strings_all_with_slash.each do |
|
94
|
-
assert_equal
|
93
|
+
@strings_all_with_slash.each do |str_from, str_to|
|
94
|
+
assert_equal str_to, str_from.bidi_translify
|
95
95
|
end
|
96
|
-
@strings_tran_without_slash.each do |
|
97
|
-
assert_equal
|
96
|
+
@strings_tran_without_slash.each do |str_from, str_to|
|
97
|
+
assert_equal str_to, str_from.bidi_translify(false)
|
98
98
|
end
|
99
99
|
end
|
100
100
|
|
101
101
|
def test_bidi_detranslify
|
102
|
-
@strings_all_with_slash.each do |
|
103
|
-
assert_equal
|
102
|
+
@strings_all_with_slash.each do |str_to, str_from|
|
103
|
+
assert_equal str_to, str_from.bidi_detranslify
|
104
104
|
end
|
105
|
-
@strings_detran_without_slash.each do |
|
106
|
-
assert_equal
|
105
|
+
@strings_detran_without_slash.each do |str_to, str_from|
|
106
|
+
assert_equal str_to, str_from.bidi_detranslify(false)
|
107
107
|
end
|
108
108
|
end
|
109
109
|
end
|
@@ -0,0 +1,17 @@
|
|
1
|
+
# Интеграция с BlueCloth - Markdown
|
2
|
+
# Сам Markdown никакой обработки типографики не производит (это делает RubyPants, но вряд ли его кто-то юзает на практике)
|
3
|
+
class MarkdownIntegrationTest < Test::Unit::TestCase
|
4
|
+
def test_integration_markdown
|
5
|
+
raise "You must have BlueCloth to test Markdown integration" and return if $skip_bluecloth
|
6
|
+
|
7
|
+
RuTils::overrides = true
|
8
|
+
assert RuTils.overrides_enabled?
|
9
|
+
assert_equal "<p>И вот «они пошли туда», и шли шли шли</p>",
|
10
|
+
BlueCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
11
|
+
|
12
|
+
RuTils::overrides = false
|
13
|
+
assert !RuTils.overrides_enabled?
|
14
|
+
assert_equal "<p>И вот \"они пошли туда\", и шли шли шли</p>",
|
15
|
+
BlueCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
16
|
+
end
|
17
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# Интеграция с RedCloth - Textile.
|
2
|
+
# Нужно иметь в виду что Textile осуществляет свою обработку типографики, которую мы подменяем!
|
3
|
+
class Redcloth3IntegrationTest < Test::Unit::TestCase
|
4
|
+
def test_integration_textile
|
5
|
+
raise "You must have RedCloth to test Textile integration" and return if $skip_redcloth
|
6
|
+
|
7
|
+
RuTils::overrides = true
|
8
|
+
assert RuTils.overrides_enabled?
|
9
|
+
|
10
|
+
assert_equal "<p>И вот «они пошли туда», и шли шли шли</p>",
|
11
|
+
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
12
|
+
|
13
|
+
RuTils::overrides = false
|
14
|
+
assert !RuTils::overrides_enabled?
|
15
|
+
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
16
|
+
RedCloth.new("*strong text* and _emphasized text_").to_html,
|
17
|
+
"Spaces should be preserved without RuTils"
|
18
|
+
|
19
|
+
RuTils::overrides = true
|
20
|
+
assert RuTils.overrides_enabled?
|
21
|
+
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
22
|
+
RedCloth.new("*strong text* and _emphasized text_").to_html,
|
23
|
+
"Spaces should be preserved"
|
24
|
+
|
25
|
+
RuTils::overrides = false
|
26
|
+
assert !RuTils.overrides_enabled?
|
27
|
+
assert_equal "<p>И вот “они пошли туда”, и шли шли шли</p>",
|
28
|
+
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
29
|
+
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,31 @@
|
|
1
|
+
# Интеграция с RedCloth - Textile.
|
2
|
+
# Нужно иметь в виду что Textile осуществляет свою обработку типографики, которую мы подменяем!
|
3
|
+
class Redcloth4IntegrationTest < Test::Unit::TestCase
|
4
|
+
def test_integration_textile
|
5
|
+
raise "You must have RedCloth to test Textile integration" and return if $skip_redcloth
|
6
|
+
|
7
|
+
RuTils::overrides = true
|
8
|
+
assert RuTils.overrides_enabled?
|
9
|
+
|
10
|
+
assert_equal "<p>И вот «они пошли туда», и шли шли шли</p>",
|
11
|
+
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
12
|
+
|
13
|
+
RuTils::overrides = false
|
14
|
+
assert !RuTils::overrides_enabled?
|
15
|
+
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
16
|
+
RedCloth.new("*strong text* and _emphasized text_").to_html,
|
17
|
+
"Spaces should be preserved without RuTils"
|
18
|
+
|
19
|
+
RuTils::overrides = true
|
20
|
+
assert RuTils.overrides_enabled?
|
21
|
+
assert_equal '<p><strong>strong text</strong> and <em>emphasized text</em></p>',
|
22
|
+
RedCloth.new("*strong text* and _emphasized text_").to_html,
|
23
|
+
"Spaces should be preserved"
|
24
|
+
|
25
|
+
RuTils::overrides = false
|
26
|
+
assert !RuTils.overrides_enabled?
|
27
|
+
assert_equal "<p>И вот “они пошли туда”, и шли шли шли</p>",
|
28
|
+
RedCloth.new('И вот "они пошли туда", и шли шли шли').to_html
|
29
|
+
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,27 @@
|
|
1
|
+
require 'action_controller/test_process'
|
2
|
+
require File.dirname(__FILE__) + '/../init.rb'
|
3
|
+
|
4
|
+
ActionController::Routing::Routes.draw { |map| map.connect ':controller/:action/:id' }
|
5
|
+
|
6
|
+
class RutiledController < ActionController::Base #:nodoc:
|
7
|
+
def overridden
|
8
|
+
raise "Overrides are off" unless RuTils::overrides_enabled?
|
9
|
+
render :inline => '<%= Time.local(2008,8,8).strftime("%B") %>'
|
10
|
+
end
|
11
|
+
def rescue_action(e); raise e; end
|
12
|
+
end
|
13
|
+
|
14
|
+
class RailsFilterTest < Test::Unit::TestCase
|
15
|
+
|
16
|
+
def setup
|
17
|
+
@controller = RutiledController.new
|
18
|
+
@request = ActionController::TestRequest.new
|
19
|
+
@response = ActionController::TestResponse.new
|
20
|
+
end
|
21
|
+
|
22
|
+
def test_overrides_preserved_in_render
|
23
|
+
assert_nothing_raised { get :overridden }
|
24
|
+
assert_response :success
|
25
|
+
assert_equal "август", @response.body
|
26
|
+
end
|
27
|
+
end
|
@@ -0,0 +1,73 @@
|
|
1
|
+
TEST_DATE = Date.parse("1983-10-15") # coincidentially...
|
2
|
+
TEST_TIME = Time.local(1983, 10, 15, 12, 15) # also coincidentially...
|
3
|
+
|
4
|
+
# Перегрузка helper'ов Rails
|
5
|
+
class RailsHelpersOverrideTest < Test::Unit::TestCase
|
6
|
+
# Вспомогательный класс для тестирования перегруженного DateHelper
|
7
|
+
class HelperStub
|
8
|
+
# для тестирования to_datetime_select_tag
|
9
|
+
def date_field; TEST_TIME; end
|
10
|
+
end
|
11
|
+
|
12
|
+
def setup
|
13
|
+
RuTils::overrides = true
|
14
|
+
# А никто и не говорил что класс должен быть один :-)
|
15
|
+
k = Class.new(HelperStub)
|
16
|
+
[ActionView::Helpers::TagHelper, ActionView::Helpers::DateHelper].each{|m| k.send(:include, m)}
|
17
|
+
@stub = k.new
|
18
|
+
end
|
19
|
+
|
20
|
+
def test_distance_of_time_in_words
|
21
|
+
assert_equal "20 минут", @stub.distance_of_time_in_words(Time.now - 20.minutes, Time.now)
|
22
|
+
end
|
23
|
+
|
24
|
+
# TODO - TextMate это не хайлайтит, и это _крайне_ достает
|
25
|
+
def test_select_month
|
26
|
+
assert_match /июль/, @stub.select_month(TEST_DATE),
|
27
|
+
"Месяц в выборе месяца должен быть указан в именительном падеже"
|
28
|
+
assert_match />7\<\/option\>/, @stub.select_month(TEST_DATE, :use_month_numbers => true),
|
29
|
+
"Хелпер select_month с номером месяца вместо названия месяца"
|
30
|
+
assert_match /10\ \-\ октябрь/, @stub.select_month(TEST_DATE, :add_month_numbers => true),
|
31
|
+
"Хелпер select_month с номером и названием месяца"
|
32
|
+
assert_match /\>июн\<\/option\>/, @stub.select_month(TEST_DATE, :use_short_month => true),
|
33
|
+
"Короткое имя месяца при использовании опции :use_short_month"
|
34
|
+
assert_match /name\=\"date\[foobar\]\"/, @stub.select_month(TEST_DATE, :field_name => "foobar"),
|
35
|
+
"Хелпер select_month должен принимать опцию :field_name"
|
36
|
+
assert_match /type\=\"hidden\".+value\=\"10\"/m, @stub.select_month(TEST_DATE, :use_hidden => true),
|
37
|
+
"Хелпер select_month должен принимать опцию :use_hidden"
|
38
|
+
end
|
39
|
+
|
40
|
+
def test_select_date
|
41
|
+
assert_match /date\_day.+date\_month.+date\_year/m, @stub.select_date(TEST_DATE),
|
42
|
+
"Хелпер select_date должен выводить поля в следующем порядке: день, месяц, год"
|
43
|
+
assert_match /декабря/, @stub.select_date(TEST_DATE),
|
44
|
+
"Имя месяца должно быть указано в родительном падеже"
|
45
|
+
assert_match /декабря/, @stub.select_date(TEST_DATE, :order => [:month, :year]),
|
46
|
+
"Хелпер select_date не позволяет опускать фрагменты, имя месяца должно быть указано в родительном падеже"
|
47
|
+
assert_match @stub.select_date, @stub.select_date(Time.now),
|
48
|
+
"Хелпер select_date без параметров работает с текущей датой"
|
49
|
+
end
|
50
|
+
|
51
|
+
def test_select_datetime
|
52
|
+
assert_match /date\_day.+date\_month.+date\_year/m, @stub.select_datetime(TEST_TIME),
|
53
|
+
"Хелпер select_datetime должен выводить поля в следующем порядке: день, месяц, год"
|
54
|
+
end
|
55
|
+
|
56
|
+
def test_html_options
|
57
|
+
if ActionView::Helpers::DateHelper::DATE_HELPERS_RECEIVE_HTML_OPTIONS
|
58
|
+
assert_match /id\=\"foobar\"/m, @stub.select_month(TEST_DATE, {}, :id => "foobar"),
|
59
|
+
"Хелпер select_month принимает html_options"
|
60
|
+
|
61
|
+
assert_match /id\=\"foobar\"/m, @stub.select_date(TEST_DATE, {}, :id => "foobar"),
|
62
|
+
"Хелпер select_date принимает html_options"
|
63
|
+
end
|
64
|
+
end
|
65
|
+
|
66
|
+
def test_instance_tag
|
67
|
+
@it = ActionView::Helpers::InstanceTag.new(:stub, :date_field, self).to_datetime_select_tag
|
68
|
+
assert_match /\>10\<.+\>октября\<.+\>1983\</m, @it,
|
69
|
+
"to_datetime_select_rag должен выводить поля в следующем порядке: день, месяц, год"
|
70
|
+
assert_match /июля/m, @it,
|
71
|
+
"to_datetime_select_tag выводит месяц в родительном падеже"
|
72
|
+
end
|
73
|
+
end
|
metadata
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: rutils
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.2.
|
4
|
+
version: 0.2.5
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Julian 'Julik' Tarkhanov
|
@@ -11,7 +11,7 @@ autorequire:
|
|
11
11
|
bindir: bin
|
12
12
|
cert_chain: []
|
13
13
|
|
14
|
-
date: 2008-
|
14
|
+
date: 2008-08-08 00:00:00 +04:00
|
15
15
|
default_executable:
|
16
16
|
dependencies:
|
17
17
|
- !ruby/object:Gem::Dependency
|
@@ -53,7 +53,10 @@ files:
|
|
53
53
|
- lib/integration/blue_cloth_override.rb
|
54
54
|
- lib/integration/integration.rb
|
55
55
|
- lib/integration/rails_date_helper_override.rb
|
56
|
+
- lib/integration/rails_pre_filter.rb
|
57
|
+
- lib/integration/red_cloth_four.rb
|
56
58
|
- lib/integration/red_cloth_override.rb
|
59
|
+
- lib/integration/red_cloth_three.rb
|
57
60
|
- lib/pluralizer/pluralizer.rb
|
58
61
|
- lib/rutils.rb
|
59
62
|
- lib/transliteration/bidi.rb
|
@@ -66,6 +69,11 @@ files:
|
|
66
69
|
- test/t_pluralize.rb
|
67
70
|
- test/t_rutils_base.rb
|
68
71
|
- test/t_transliteration.rb
|
72
|
+
- test/test_integration_bluecloth.rb
|
73
|
+
- test/test_integration_redcloth3.rb
|
74
|
+
- test/test_integration_redcloth4.rb
|
75
|
+
- test/test_rails_filter.rb
|
76
|
+
- test/test_rails_helpers.rb
|
69
77
|
has_rdoc: true
|
70
78
|
homepage: http://rutils.rubyforge.org
|
71
79
|
post_install_message:
|