rutils 0.1.2 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -7,166 +7,166 @@ end
7
7
  # "вот мы и здесь".translify => "vot my i zdes"
8
8
  # "vot my i zdes".detranslify => "вот мы и здесь"
9
9
  module RuTils::Transliteration::Simple
10
- TABLE = {
11
- "Ґ"=>"G","Ё"=>"YO","Є"=>"E","Ї"=>"YI","І"=>"I",
12
- "і"=>"i","ґ"=>"g","ё"=>"yo","№"=>"#","є"=>"e",
13
- "ї"=>"yi","А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
14
- "Д"=>"D","Е"=>"E","Ж"=>"ZH","З"=>"Z","И"=>"I",
15
- "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
16
- "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
17
- "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH",
18
- "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"'","Ы"=>"YI","Ь"=>"",
19
- "Э"=>"E","Ю"=>"YU","Я"=>"YA","а"=>"a","б"=>"b",
20
- "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"zh",
21
- "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
22
- "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
23
- "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
24
- "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'",
25
- "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"
26
- }.sort do | one, two|
27
- two[1].size <=> one[1].size
28
- end
29
-
30
- # Заменяет кириллицу в строке на латиницу
31
- def self.translify(str)
32
- s = str.clone
33
- TABLE.each do | translation |
34
- s = s.gsub(/#{translation[0]}/, translation[1])
35
- end
36
- s
37
- end
38
-
39
- # Заменяет латиницу на кириллицу
40
- def self.detranslify(str)
41
- s = str.clone
42
- TABLE.each do | translation |
43
- s.gsub!(/#{translation[1]}/, translation[0])
44
- end
45
- s
46
- end
47
-
48
- # Транслитерирует строку, делая ее пригодной для применения как имя директории или URL
49
- def self.dirify(string)
50
- st = self.translify(string)
10
+ TABLE = {
11
+ "Ґ"=>"G","Ё"=>"YO","Є"=>"E","Ї"=>"YI","І"=>"I",
12
+ "і"=>"i","ґ"=>"g","ё"=>"yo","№"=>"#","є"=>"e",
13
+ "ї"=>"yi","А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
14
+ "Д"=>"D","Е"=>"E","Ж"=>"ZH","З"=>"Z","И"=>"I",
15
+ "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
16
+ "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
17
+ "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH",
18
+ "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"'","Ы"=>"YI","Ь"=>"",
19
+ "Э"=>"E","Ю"=>"YU","Я"=>"YA","а"=>"a","б"=>"b",
20
+ "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"zh",
21
+ "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
22
+ "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
23
+ "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
24
+ "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'",
25
+ "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"
26
+ }.sort do | one, two|
27
+ two[1].size <=> one[1].size
28
+ end
29
+
30
+ # Заменяет кириллицу в строке на латиницу
31
+ def self.translify(str)
32
+ s = str.clone
33
+ TABLE.each do | translation |
34
+ s = s.gsub(/#{translation[0]}/, translation[1])
35
+ end
36
+ s
37
+ end
38
+
39
+ # Заменяет латиницу на кириллицу
40
+ def self.detranslify(str)
41
+ s = str.clone
42
+ TABLE.each do | translation |
43
+ s.gsub!(/#{translation[1]}/, translation[0])
44
+ end
45
+ s
46
+ end
47
+
48
+ # Транслитерирует строку, делая ее пригодной для применения как имя директории или URL
49
+ def self.dirify(string)
50
+ st = self.translify(string)
51
51
  st.gsub!(/(\s\&\s)|(\s\&amp\;\s)/, ' and ') # convert & to "and"
52
52
  st.gsub!(/\W/, ' ') #replace non-chars
53
53
  st.gsub!(/(_)$/, '') #trailing underscores
54
54
  st.gsub!(/^(_)/, '') #leading unders
55
- st.strip.translify.gsub(/(\s)/,'-').downcase.squeeze
56
- end
55
+ st.strip.translify.gsub(/(\s)/,'-').downcase.squeeze
56
+ end
57
57
  end
58
-
58
+
59
59
  # Реализует транслитерацию "в обе стороны", дающую возможность автоматически использовать URL как ключ записи
60
60
  module RuTils::Transliteration::BiDi #:nodoc:
61
- TABLE_TO = {
62
- "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G","Д"=>"D",
63
- "Е"=>"E","Ё"=>"JO","Ж"=>"ZH","З"=>"Z","И"=>"I",
64
- "Й"=>"JJ","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
65
- "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
66
- "У"=>"U","Ф"=>"F","Х"=>"KH","Ц"=>"C","Ч"=>"CH",
67
- "Ш"=>"SH","Щ"=>"SHH","Ъ"=>"_~","Ы"=>"Y","Ь"=>"_'",
68
- "Э"=>"EH","Ю"=>"JU","Я"=>"JA","а"=>"a","б"=>"b",
69
- "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ё"=>"jo",
70
- "ж"=>"zh","з"=>"z","и"=>"i","й"=>"jj","к"=>"k",
71
- "л"=>"l","м"=>"m","н"=>"n","о"=>"o","п"=>"p",
72
- "р"=>"r","с"=>"s","т"=>"t","у"=>"u","ф"=>"f",
73
- "х"=>"kh","ц"=>"c","ч"=>"ch","ш"=>"sh","щ"=>"shh",
74
- "ъ"=>"~","ы"=>"y","ь"=>"'","э"=>"eh","ю"=>"ju",
75
- "я"=>"ja",
76
- # " "=>"__","_"=>"__"
77
- # так сразу не получится, будут проблемы с "Ь"=>"_'"
78
- }.sort do |one, two|
79
- two[1].jsize <=> one[1].jsize
80
- end
81
-
82
- TABLE_FROM = TABLE_TO.unshift([" ","__"]).clone
83
- TABLE_TO.unshift(["_","__"])
84
-
85
- def self.translify(str, allow_slashes = true)
86
- slash = allow_slashes ? '/' : '';
87
-
88
- s = str.clone.gsub(/[^\- _0-9a-zA-ZА-ёЁ#{slash}]/, '')
89
- lang_fr = s.scan(/[А-ёЁ ]+/)
90
- lang_fr.each do |fr|
91
- TABLE_TO.each do | translation |
92
- fr.gsub!(/#{translation[0]}/, translation[1])
93
- end
94
- end
95
-
96
- lang_sr = s.scan(/[0-9A-Za-z\_\-\.\/\']+/)
97
-
98
- string = ""
99
- if s =~ /\A[А-ёЁ ]/
100
- lang_fr, lang_sr = lang_sr, lang_fr
101
- string = "+"
102
- end
103
-
104
- 0.upto([lang_fr.length, lang_sr.length].min-1) do |x|
105
- string += lang_sr[x] + "+" + lang_fr[x] + "+";
106
- end
107
-
108
- if (lang_fr.length < lang_sr.length)
109
- string += lang_sr[lang_sr.length-1]
110
- else
111
- string[0, string.length-1]
112
- end
113
- end
114
-
115
- def self.detranslify(str, allow_slashes = true)
116
- slash = allow_slashes ? '/' : '';
117
-
118
- str.split('/').inject(out = "") do |out, pg|
119
- strings = pg.split('+')
120
- 1.step(strings.length-1, 2) do |x|
121
- TABLE_FROM.each do | translation |
122
- strings[x].gsub!(/#{translation[1]}/, translation[0])
123
- end
124
- end
125
- out << slash << strings.to_s
126
- end
127
- out[slash.length, out.length-slash.length]
128
- end
61
+ TABLE_TO = {
62
+ "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G","Д"=>"D",
63
+ "Е"=>"E","Ё"=>"JO","Ж"=>"ZH","З"=>"Z","И"=>"I",
64
+ "Й"=>"JJ","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
65
+ "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
66
+ "У"=>"U","Ф"=>"F","Х"=>"KH","Ц"=>"C","Ч"=>"CH",
67
+ "Ш"=>"SH","Щ"=>"SHH","Ъ"=>"_~","Ы"=>"Y","Ь"=>"_'",
68
+ "Э"=>"EH","Ю"=>"JU","Я"=>"JA","а"=>"a","б"=>"b",
69
+ "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ё"=>"jo",
70
+ "ж"=>"zh","з"=>"z","и"=>"i","й"=>"jj","к"=>"k",
71
+ "л"=>"l","м"=>"m","н"=>"n","о"=>"o","п"=>"p",
72
+ "р"=>"r","с"=>"s","т"=>"t","у"=>"u","ф"=>"f",
73
+ "х"=>"kh","ц"=>"c","ч"=>"ch","ш"=>"sh","щ"=>"shh",
74
+ "ъ"=>"~","ы"=>"y","ь"=>"'","э"=>"eh","ю"=>"ju",
75
+ "я"=>"ja",
76
+ # " "=>"__","_"=>"__"
77
+ # так сразу не получится, будут проблемы с "Ь"=>"_'"
78
+ }.sort do |one, two|
79
+ two[1].jsize <=> one[1].jsize
80
+ end
81
+
82
+ TABLE_FROM = TABLE_TO.unshift([" ","__"]).clone
83
+ TABLE_TO.unshift(["_","__"])
84
+
85
+ def self.translify(str, allow_slashes = true)
86
+ slash = allow_slashes ? '/' : '';
87
+
88
+ s = str.clone.gsub(/[^\- _0-9a-zA-ZА-ёЁ#{slash}]/, '')
89
+ lang_fr = s.scan(/[А-ёЁ ]+/)
90
+ lang_fr.each do |fr|
91
+ TABLE_TO.each do | translation |
92
+ fr.gsub!(/#{translation[0]}/, translation[1])
93
+ end
94
+ end
95
+
96
+ lang_sr = s.scan(/[0-9A-Za-z\_\-\.\/\']+/)
97
+
98
+ string = ""
99
+ if s =~ /\A[А-ёЁ ]/
100
+ lang_fr, lang_sr = lang_sr, lang_fr
101
+ string = "+"
102
+ end
103
+
104
+ 0.upto([lang_fr.length, lang_sr.length].min-1) do |x|
105
+ string += lang_sr[x] + "+" + lang_fr[x] + "+";
106
+ end
107
+
108
+ if (lang_fr.length < lang_sr.length)
109
+ string += lang_sr[lang_sr.length-1]
110
+ else
111
+ string[0, string.length-1]
112
+ end
113
+ end
114
+
115
+ def self.detranslify(str, allow_slashes = true)
116
+ slash = allow_slashes ? '/' : '';
117
+
118
+ str.split('/').inject(out = "") do |out, pg|
119
+ strings = pg.split('+')
120
+ 1.step(strings.length-1, 2) do |x|
121
+ TABLE_FROM.each do | translation |
122
+ strings[x].gsub!(/#{translation[1]}/, translation[0])
123
+ end
124
+ end
125
+ out << slash << strings.to_s
126
+ end
127
+ out[slash.length, out.length-slash.length]
128
+ end
129
129
  end
130
130
 
131
131
  # Реализует транслитерацию любого объекта, реализующего String или to_s
132
132
  module RuTils::Transliteration::StringFormatting
133
-
134
- #Транслитерирует строку в латиницу, и возвращает измененную строку
135
- def translify
136
- RuTils::Transliteration::Simple::translify(self.to_s)
137
- end
138
-
139
- #Транслитерирует строку, меняя объект
140
- def translify!
141
- self.replace(self.translify)
142
- end
143
-
144
- # Транслитерирует строку, делая ее пригодной для применения как имя директории или URL
145
- def dirify
146
- RuTils::Transliteration::Simple::dirify(self.to_s)
147
- end
148
-
149
- # Транслитерирует строку (взаимно-однозначный транслит), и возвращает измененную строку
150
- def bidi_translify(allow_slashes = true)
151
- RuTils::Transliteration::BiDi::translify(self.to_s, allow_slashes)
152
- end
153
-
154
- # Транслитерирует строку (взаимно-однозначный транслит), меняя объект
155
- def bidi_translify!(allow_slashes = true)
156
- self.replace(RuTils::Transliteration::BiDi::translify(self.to_s, allow_slashes))
157
- end
158
-
159
- # Заменяет латиницу на кириллицу (взаимно-однозначный транслит), меняя объект
160
- def bidi_detranslify!(allow_slashes = true)
161
- self.replace(RuTils::Transliteration::BiDi::detranslify(self.to_s, allow_slashes))
162
- end
163
-
164
- # Заменяет латиницу на кириллицу (взаимно-однозначный транслит), и возвращает измененную строку
165
- def bidi_detranslify(allow_slashes = true)
166
- RuTils::Transliteration::BiDi::detranslify(self.to_s, allow_slashes)
167
- end
133
+
134
+ #Транслитерирует строку в латиницу, и возвращает измененную строку
135
+ def translify
136
+ RuTils::Transliteration::Simple::translify(self.to_s)
137
+ end
138
+
139
+ #Транслитерирует строку, меняя объект
140
+ def translify!
141
+ self.replace(self.translify)
142
+ end
143
+
144
+ # Транслитерирует строку, делая ее пригодной для применения как имя директории или URL
145
+ def dirify
146
+ RuTils::Transliteration::Simple::dirify(self.to_s)
147
+ end
148
+
149
+ # Транслитерирует строку (взаимно-однозначный транслит), и возвращает измененную строку
150
+ def bidi_translify(allow_slashes = true)
151
+ RuTils::Transliteration::BiDi::translify(self.to_s, allow_slashes)
152
+ end
153
+
154
+ # Транслитерирует строку (взаимно-однозначный транслит), меняя объект
155
+ def bidi_translify!(allow_slashes = true)
156
+ self.replace(RuTils::Transliteration::BiDi::translify(self.to_s, allow_slashes))
157
+ end
158
+
159
+ # Заменяет латиницу на кириллицу (взаимно-однозначный транслит), меняя объект
160
+ def bidi_detranslify!(allow_slashes = true)
161
+ self.replace(RuTils::Transliteration::BiDi::detranslify(self.to_s, allow_slashes))
162
+ end
163
+
164
+ # Заменяет латиницу на кириллицу (взаимно-однозначный транслит), и возвращает измененную строку
165
+ def bidi_detranslify(allow_slashes = true)
166
+ RuTils::Transliteration::BiDi::detranslify(self.to_s, allow_slashes)
167
+ end
168
168
  end
169
169
 
170
170
  class Object::String
171
- include RuTils::Transliteration::StringFormatting
171
+ include RuTils::Transliteration::StringFormatting
172
172
  end
data/test/run_tests.rb CHANGED
@@ -1,4 +1,4 @@
1
1
  Dir.entries(File.dirname(__FILE__)).each do | it|
2
- next unless it =~ /t_/
3
- require File.dirname(__FILE__) + '/' + it.gsub(/\.rb$/, '')
2
+ next unless it =~ /t_/
3
+ require File.dirname(__FILE__) + '/' + it.gsub(/\.rb$/, '')
4
4
  end
data/test/t_datetime.rb CHANGED
@@ -3,10 +3,36 @@ require 'test/unit'
3
3
  require File.dirname(__FILE__) + '/../lib/rutils'
4
4
 
5
5
  class DistanceOfTimeTest < Test::Unit::TestCase
6
- def test_distance_of_time_in_words
7
- assert_equal "меньше минуты", RuTils::DateTime::distance_of_time_in_words(0, 50)
8
- assert_equal "2 минуты", RuTils::DateTime::distance_of_time_in_words(0, 140)
9
- assert_equal "около 2 часов", RuTils::DateTime::distance_of_time_in_words(0, 60*114)
10
- assert_equal "около 3 часов", RuTils::DateTime::distance_of_time_in_words(0, 60*120+60*60)
11
- end
6
+ def test_distance_of_time_in_words
7
+ assert_equal "меньше минуты", RuTils::DateTime::distance_of_time_in_words(0, 50)
8
+ assert_equal "2 минуты", RuTils::DateTime::distance_of_time_in_words(0, 140)
9
+ assert_equal "около 2 часов", RuTils::DateTime::distance_of_time_in_words(0, 60*114)
10
+ assert_equal "около 3 часов", RuTils::DateTime::distance_of_time_in_words(0, 60*120+60*60)
11
+ end
12
+ end
13
+
14
+ class StrftimeRuTest < Test::Unit::TestCase
15
+ def test_strftime_ru
16
+ @@old_overrides = RuTils::overrides_enabled?
17
+
18
+ RuTils::overrides = true
19
+ assert_equal "Сб, Суббота, Дек, Декабрь", Time.local(2005,"dec",31).strftime("%a, %A, %b, %B")
20
+ assert_equal "%a, %A, %b, %B", Time.local(2005,"dec",31).strftime("%%a, %%A, %%b, %%B")
21
+ assert_equal "%Сб, %Суббота, %Дек, %Декабрь", Time.local(2005,"dec",31).strftime("%%%a, %%%A, %%%b, %%%B")
22
+ assert_equal "Сегодня: 31 Декабрь, Суббота, 2005 год", Time.local(2005,"dec",31).strftime("Сегодня: %d %B, %A, %Y год")
23
+
24
+ date = Date.new(2005, 11, 9)
25
+ assert_equal "Ноя Ноябрь Ср Среда", "#{Date::RU_ABBR_MONTHNAMES[date.mon]} #{Date::RU_MONTHNAMES[date.mon]} #{Date::RU_ABBR_DAYNAMES[date.wday]} #{Date::RU_DAYNAMES[date.wday]}"
26
+
27
+ RuTils::overrides = false
28
+ assert_equal "Sat, Saturday, Dec, December", Time.local(2005,"dec",31).strftime("%a, %A, %b, %B")
29
+ assert_equal "%a, %A, %b, %B", Time.local(2005,"dec",31).strftime("%%a, %%A, %%b, %%B")
30
+ assert_equal "%Sat, %Saturday, %Dec, %December", Time.local(2005,"dec",31).strftime("%%%a, %%%A, %%%b, %%%B")
31
+ assert_equal "Сегодня: 31 December, Saturday, 2005 год", Time.local(2005,"dec",31).strftime("Сегодня: %d %B, %A, %Y год")
32
+
33
+ date = Date.new(2005, 11, 9)
34
+ assert_equal "Nov November Wed Wednesday", "#{Date::ABBR_MONTHNAMES[date.mon]} #{Date::MONTHNAMES[date.mon]} #{Date::ABBR_DAYNAMES[date.wday]} #{Date::DAYNAMES[date.wday]}"
35
+
36
+ RuTils::overrides = @@old_overrides
37
+ end
12
38
  end