st_tools 0.3.18 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 1b75103e477ed3bfa3fe90d783b6d3322e5f6cab
4
- data.tar.gz: 72d7f8f22f2ca4e4d8f47a76364ec7a38d9dbb4d
3
+ metadata.gz: 9a7fcb770812f74e220c7964ea4f065807e643d6
4
+ data.tar.gz: 692c8ba12cd6a0bc6d55f01e78e3b22653bc5978
5
5
  SHA512:
6
- metadata.gz: d6bcfb61c19bcc4bd889b60de26a646e077385e3c3ce218a1de6892e7d094212a14cbccb054dfb41820a16db5efe75e8146c18ebb3bea4c25c2b2bf51669bcf1
7
- data.tar.gz: 69ffea0a6edf61a2de3f5f798ac82dce656f1eba7b3a755725708c47a3987b5e29f84be8e9010335ed7ff46a10769a45d35d35dd67ca02cf50e96084d82e0eec
6
+ metadata.gz: 9b3ccdc959bbaa8072d2753949442ec04cd56a1035ba0ad96106dac7edf8d3c1209d3b79658811715e9412fcfc068bb66a13cf7a328a40dab4240586af180a8e
7
+ data.tar.gz: d5c7bbe1d071cc8d3b60581041f64e902d2e11749844115f61ea4ac03126b221a541cc92ee7457472fca679af07b3da16fe8fc5fd1130ed7b2239e0b4b3b9f61
data/README.md CHANGED
@@ -23,20 +23,32 @@ gem 'st_tools'
23
23
 
24
24
  # Зависимости
25
25
 
26
- Для работы гема требуется Ruby не младше версии 2.0.0. StTools не привязана к Rails и может использоваться в CLI-приложениях.
26
+ Для работы гема требуется Ruby не младше версии 2.2.0. StTools не привязана к Rails и может использоваться в CLI-приложениях.
27
27
  Класс StTools::ProgressBar является надстройкой над гемом 'progressbar-ruby'.
28
28
 
29
29
  ## Использование
30
30
 
31
31
  Часть методов библиотеки поддерживают русскую и английскую локализацию.
32
32
  Поскольку все методы StTools могут вызываться без создания экземпляра класса - вызов конструктура класса отсутствует.
33
- Поэтому перед работой библиотеки рекомендуется вызвать StTools::Setup.setup(:ru или :en) для загрузки файлов локализации.
33
+ Ряд методов библиотеки требуют настройки локализации. Для этого, в приложении Ruby CLI нужно использовать:
34
+
35
+ ```ruby
36
+ StTools.configure { |config| config.locale = :ru }
37
+ ```
38
+
39
+ В приложении Rails необходимо создать файл `/initializers/st_tools.rb`, и включить в него:
40
+ ```ruby
41
+ StTools.configure do |config|
42
+ config.locale = :ru
43
+ end
44
+ ```
34
45
 
35
46
  ### StTools::Human
36
47
 
37
48
  Вы вызываете в любой момент StTools::Human.memory и узнаете текущий размер памяти, занимаемый приложением (процессом)
38
49
 
39
50
  ```ruby
51
+ StTools.configure { |config| config.locale = :ru }
40
52
  StTools::Human.memory # => 14 кбайт
41
53
  StTools::Human.memory # => 45,3 Мбайт
42
54
  StTools::Human.memory # => 2,6 Гбайт
@@ -45,6 +57,7 @@ StTools::Human.memory # => 2,6 Гбайт
45
57
  Вы вызываете StTools::Human.bytes и перевести любое значение в человеко-удобный вид. Метод можно использовать для показа размера файла
46
58
 
47
59
  ```ruby
60
+ StTools.configure { |config| config.locale = :ru }
48
61
  StTools::Human.bytes(345) # => 345 байт
49
62
  StTools::Human.bytes(14653) # => 14,5 кбайт
50
63
  StTools::Human.bytes(23653763) # => 23,4 Мбайт
@@ -54,6 +67,7 @@ StTools::Human.bytes(23653763) # => 23,4 Мбайт
54
67
  Метод можно использовать для показа, например, суммы денег
55
68
 
56
69
  ```ruby
70
+ StTools.configure { |config| config.locale = :ru }
57
71
  StTools::Human.number(345) # => 345
58
72
  StTools::Human.number(14653) # => 14,6 тыс.
59
73
  StTools::Human.number(23653763) # => 23,7 млн.
@@ -63,6 +77,7 @@ StTools::Human.number(23653763) # => 23,7 млн.
63
77
  число цифр после запятой, и автоматически конвертировать точку в звпятую
64
78
 
65
79
  ```ruby
80
+ StTools.configure { |config| config.locale = :ru }
66
81
  StTools::Human.pretty_number(345) # => 345
67
82
  StTools::Human.pretty_number(345, round: 2) # => 345,00
68
83
  StTools::Human.pretty_number(75345, round: 1) # => 75 345,0
@@ -73,14 +88,14 @@ StTools::Human.pretty_number('1675345.763', round: 1) # => 1 675 345,7
73
88
  Вы имеете возможность узнать разницу между текущим временем и временем какого-либо события.
74
89
 
75
90
  ```ruby
76
- StTools::Setup.setup(:ru)
91
+ StTools.configure { |config| config.locale = :ru }
77
92
  StTools::Human.human_ago(DateTime.new(2014,12,31), true) # => 4 месяца 21 день назад
78
93
  StTools::Human.human_ago(DateTime.new(2013,08,01), false) # => 1 год 8 месяца
79
94
  StTools::Human.human_ago(Time.now - 15, true) # => 15 секунд назад
80
95
  ```
81
96
 
82
97
  ```ruby
83
- StTools::Setup.setup(:en)
98
+ StTools.configure { |config| config.locale = :en }
84
99
  StTools::Human.human_ago(DateTime.new(2014,12,31), true) # => 4 months 21 days ago
85
100
  StTools::Human.human_ago(DateTime.new(2013,08,01), false) # => 1 year 8 months
86
101
  StTools::Human.human_ago(Time.now - 15, true) # => 15 seconds ago
@@ -96,17 +111,17 @@ StTools::Human.human_ago(Time.now - 15, true) # => 15 seconds
96
111
  не временная метка, а просто количество секунд между двумя событиями.
97
112
 
98
113
  ```ruby
99
- StTools::Setup.setup(:ru)
114
+ StTools.configure { |config| config.locale = :ru }
100
115
  StTools::Human.seconds_ago(DateTime.new(2014,12,31), true) # => 4 months 21 days ago
101
116
  StTools::Human.seconds_ago(DateTime.new(2013,08,01), false) # => 1 year 8 months
102
117
  StTools::Human.seconds_ago(Time.now - 15, true) # => 15 seconds ago
103
118
  ```
104
119
 
105
120
 
106
- Вы имеете форматировать дату и время в соответствии с правилами русского и английского языка.
121
+ Вы можете форматировать дату и время в соответствии с правилами русского и английского языка.
107
122
 
108
123
  ```ruby
109
- StTools::Setup.setup(:ru)
124
+ StTools.configure { |config| config.locale = :ru }
110
125
  StTools::Human.format_time(Time.now, :full, :full) # => 28 апреля 2015 г. 10:45:23
111
126
  StTools::Human.format_time(Time.now, :date, :full) # => 28 апреля 2015 г.
112
127
  StTools::Human.format_time(Time.now, :time, :full) # => 10:45:23
@@ -116,7 +131,7 @@ StTools::Human.format_time(Time.now, :time, :short) # => 10:45
116
131
  ```
117
132
 
118
133
  ```ruby
119
- StTools::Setup.setup(:en)
134
+ StTools.configure { |config| config.locale = :en }
120
135
  StTools::Human.format_time(Time.now, :full, :full) # => April 28, 2015 09:45:23 am
121
136
  StTools::Human.format_time(Time.now, :date, :full) # => April 28, 2015
122
137
  StTools::Human.format_time(Time.now, :time, :full) # => 09:45:23 am
@@ -125,6 +140,20 @@ StTools::Human.format_time(Time.now, :date, :short) # => 04/28/2015
125
140
  StTools::Human.format_time(Time.now, :time, :short) # => 09:45 am
126
141
  ```
127
142
 
143
+ Новая версия данной функции имеет более прстой и понятный синтаксис. Первый параметр - формат даты, второй - времени.
144
+
145
+ ```ruby
146
+ StTools.configure { |config| config.locale = :ru }
147
+ StTools::Human.format_time2(Time.now, :human, :full) #=> "30 апреля 2015 г. 08:54:34"
148
+ StTools::Human.format_time2(Time.now, :human, :full, god: false) #=> "30 апреля 2015 08:54:34"
149
+ StTools::Human.format_time2(Time.now, :human, :short) #=> "30 апреля 2015 г. 8:54"
150
+ StTools::Human.format_time2(Time.now, :human, :none) #=> "30 апреля 2015 г."
151
+ StTools::Human.format_time2(Time.now, :full, :full) #=> "30/04/2015 08:54:34"
152
+ StTools::Human.format_time2(Time.now, :short, :short) #=> "30/04/15 8:54"
153
+ StTools::Human.format_time2(Time.now, :none, :full) #=> "08:54:34"
154
+ StTools::Human.format_time2(Time.now, :none, :short) #=> "8:54"
155
+ ````
156
+
128
157
  Вы можете подмешать модуль `StTools::Module` в классы String, Integer, Time.
129
158
 
130
159
  ```ruby
data/lib/i18n/en.yml CHANGED
@@ -33,6 +33,13 @@ en:
33
33
  date_short: "%m/%d/%Y"
34
34
  full_short: "%m/%d/%Y %I:%M:%S %P"
35
35
  time_short: "%I:%M %P"
36
+
37
+ # Values for format_time2
38
+ tfull: "%I:%M:%S %P"
39
+ tshort: "%I:%M %P"
40
+ dhuman: "%B %-d, %Y"
41
+ dfull: "%m/%d/%Y"
42
+ dshort: "%-m/%-d/%Y"
36
43
  date:
37
44
  <<: *defaults
38
45
  time:
@@ -71,7 +78,11 @@ en:
71
78
  two: seconds
72
79
  other: seconds
73
80
 
74
- string:
81
+ st_tools:
82
+ bytes: "b,kb,Mb,Gb,Tb,Pb"
83
+ numbers: ",k,m,b,t"
84
+ numbers_separator: ""
75
85
  pretty_list:
76
86
  and: and
77
87
  or: or
88
+
data/lib/i18n/ru.yml CHANGED
@@ -12,6 +12,13 @@ ru:
12
12
  date_short: "%d/%m/%Y"
13
13
  full_short: "%d/%m/%Y %H:%M"
14
14
  time_short: "%H:%M"
15
+
16
+ # Значения для format_time2
17
+ tfull: "%H:%M:%S"
18
+ tshort: "%H:%M"
19
+ dhuman: "%-d %B %Y"
20
+ dfull: "%d/%m/%Y"
21
+ dshort: "%-d/%-m/%Y"
15
22
  date:
16
23
  <<: *defaults
17
24
  time:
@@ -48,7 +55,10 @@ ru:
48
55
  two: секунды
49
56
  other: секунд
50
57
 
51
- string:
58
+ st_tools:
59
+ bytes: "байт,кбайт,Мбайт,Гбайт,Тбайт,Пбайт"
60
+ numbers: ",тыс.,млн.,млрд.,трлн."
61
+ numbers_separator: " "
52
62
  pretty_list:
53
63
  and: и
54
64
  or: или
data/lib/st_tools.rb CHANGED
@@ -4,6 +4,7 @@ require "st_tools/version"
4
4
 
5
5
  require 'ruby-progressbar'
6
6
  require 'yaml'
7
+ require 'i18n'
7
8
 
8
9
  module StTools
9
10
  require "st_tools/common"
@@ -19,8 +20,65 @@ module StTools
19
20
  require 'modules/time'
20
21
  require 'modules/fias'
21
22
 
22
- class Setup
23
+ # Use tutorial https://robots.thoughtbot.com/mygem-configure-block
24
+ class << self
25
+ attr_accessor :configuration
26
+ end
27
+
28
+ def self.configure
29
+ self.configuration ||= Configuration.new
30
+ yield(configuration)
31
+ end
32
+
33
+ class Configuration
34
+ attr_reader :locale
35
+ attr_accessor :bytes_array
36
+ attr_accessor :numbers_array
23
37
 
38
+ def initialize
39
+ locale = :ru
40
+ end
41
+
42
+ def locale=(val)
43
+ ::I18n.load_path += Dir[File.join(File.dirname(__dir__), '/lib/i18n/*.yml')]
44
+ ::I18n.backend.load_translations
45
+ case val.to_sym
46
+ when :ru, :en
47
+ @locale = val.to_sym
48
+ else
49
+ @locale = :ru
50
+ end
51
+ rebuild_bytes_array
52
+ rebuild_numbers_array
53
+ end
54
+
55
+ def rebuild_bytes_array
56
+ keys = I18n.t('st_tools.bytes', locale: @locale).split(",")
57
+ keys.map! { |x| x.strip }
58
+ raise "Must be 6 elements in array #{keys.inspect}" if keys.count != 6
59
+ @bytes_array = Hash.new
60
+ inc_value = 1024
61
+ keys.each do |key|
62
+ @bytes_array[key] = inc_value
63
+ inc_value *= 1024
64
+ end
65
+ end
66
+
67
+ def rebuild_numbers_array
68
+ keys = I18n.t('st_tools.numbers', locale: @locale).split(",")
69
+ keys.map! { |x| x.strip }
70
+ raise "Must be 5 elements in array #{keys.inspect}" if keys.count != 5
71
+ @numbers_array = Hash.new
72
+ inc_value = 1000
73
+ keys.each do |key|
74
+ @numbers_array[key] = inc_value
75
+ inc_value *= 1000
76
+ end
77
+ end
78
+
79
+ end
80
+
81
+ class Setup
24
82
  # Метод загрузки файлов локализации для методов форматирования времени. Принимает значения [:en, :ru]
25
83
  #
26
84
  # @param [Object] locale - язык локализации, поддерживается :ru, :en. Если передена неизвестная локализация
@@ -29,6 +87,7 @@ module StTools
29
87
  def self.setup(locale)
30
88
  locale = :ru unless [:ru, :en].include?(locale)
31
89
  self.setup_locale(locale)
90
+ warn "[DEPRECATION] setup is will deprecated."
32
91
  end
33
92
 
34
93
  private
@@ -3,47 +3,42 @@ module StTools
3
3
 
4
4
 
5
5
  # Метод форматирует число, добавляя суффиксы 'тыс.', 'млн.' и пр.
6
+ # Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.
6
7
  #
7
8
  # @param [Integer] val исходное числовое значение
8
9
  # @return [String] строка вида "512,4 тыс."
9
10
  # @example Примеры использования
11
+ # StTools.configure { |config| config.locale = :ru }
10
12
  # StTools::Human.number(123) #=> "123"
11
13
  # StTools::Human.number(14563) #=> "14 тыс."
12
14
  # StTools::Human.number(763552638) #=> "763.6 млн."
13
15
  def self.number(val)
14
- # todo: локлаизовать через i18N
15
- # noinspection RubyStringKeysInHashInspection
16
- arr = {'' => 1000, 'тыс.' => 1000 * 1000, 'млн.' => 1000 * 1000 * 1000,
17
- 'млрд.' => 1000 * 1000 * 1000 * 1000, 'трлн.' => 1000 * 1000 * 1000 * 1000 * 1000}
18
-
19
- arr.each_pair do |e, s|
16
+ StTools.configuration.numbers_array.each_pair do |e, s|
20
17
  if val < s
21
- if ['', ' тыс.'].include?(e)
22
- return "#{(val.to_f / (s / 1000)).round(0)} #{e}"
18
+ if s <= 1000*1000
19
+ return "#{(val.to_f / (s / 1000)).round(0)}#{I18n.t('st_tools.numbers_separator', locale: StTools.configuration.locale)}#{e}"
23
20
  else
24
- return "#{(val.to_f / (s / 1000)).round(1)} #{e}"
21
+ return "#{(val.to_f / (s / 1000)).round(1)}#{I18n.t('st_tools.numbers_separator', locale: StTools.configuration.locale)}#{e}"
25
22
  end
26
23
  end
27
24
  end
28
25
  end
29
26
 
30
27
  # Метод форматирует число, добавляя суффиксы 'кбайт', 'Мбайт' и др.
28
+ # Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.
31
29
  #
32
30
  # @param [Integer] val исходное числовое значение в байтах
33
31
  # @return [String] строка вида "512,4 Мбайт"
34
32
  # @example Примеры использования
33
+ # StTools.configure { |config| config.locale = :ru }
35
34
  # StTools::Human.bytes(123) #=> "123 байта"
36
35
  # StTools::Human.bytes(14563) #=> "14 кбайт"
37
36
  # StTools::Human.bytes(763552638) #=> "728.2 Мбайт"
38
37
  def self.bytes(val)
39
- # todo: локлаизовать через i18N
40
38
  # noinspection RubyStringKeysInHashInspection
41
- arr = {'байт' => 1024, 'кбайт' => 1024 * 1024, 'Мбайт' => 1024 * 1024 * 1024,
42
- 'Гбайт' => 1024 * 1024 * 1024 * 1024, 'Тбайт' => 1024 * 1024 * 1024 * 1024 * 1024}
43
-
44
- arr.each_pair do |e, s|
39
+ StTools.configuration.bytes_array.each_pair do |e, s|
45
40
  if val < s
46
- if %w(байт кбайт).include?(e)
41
+ if s <= 1024*1024
47
42
  return "#{(val.to_f / (s / 1024)).round(0)} #{e}"
48
43
  else
49
44
  return "#{(val.to_f / (s / 1024)).round(1)} #{e}"
@@ -61,13 +56,13 @@ module StTools
61
56
  end
62
57
 
63
58
  # Метод переводит DateTime в строку на русском или иных языках вида "4 дня 23 часа назад".
64
- # Предварительно необходимо вызвать StTools.setup(:ru или :en).
59
+ # Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.
65
60
  #
66
61
  # @param [DateTime] time время и дата
67
62
  # @param [Boolean] ago true, если надо добавить слово "назад" в конец строки
68
63
  # @return [String] строка вида "3 дня 12 часов" или "3 дня 12 часов назад"
69
64
  # @example Примеры использования
70
- # StTools::Setup.setup(:ru)
65
+ # StTools.configure { |config| config.locale = :ru }
71
66
  # StTools::Human.human_ago(Time.now - 23, true) #=> "23 секунды назад"
72
67
  # StTools::Human.human_ago(Time.now - 24553, false) #=> 6 часов 49 минут"
73
68
  # StTools::Human.human_ago(Time.now) #=> "сейчас"
@@ -75,37 +70,39 @@ module StTools
75
70
  now = self.to_time(Time.now.strftime('%Y-%m-%d %H:%M:%S UTC'))
76
71
  slf = self.to_time(time.strftime('%Y-%m-%d %H:%M:%S UTC'))
77
72
  secs = (now - slf).to_i
78
- return I18n.t('common.ago.very_long') if time.year < 1800
79
- return I18n.t('common.ago.just_now') if secs > -1 && secs < 1
73
+ return I18n.t('common.ago.very_long', locale: StTools.configuration.locale) if time.year < 1800
74
+ return I18n.t('common.ago.just_now', locale: StTools.configuration.locale) if secs > -1 && secs < 1
80
75
  return '' if secs <= -1
81
76
  pair = self.ago_in_words_pair(secs)
82
- pair << I18n.t("common.ago.ago_word") if ago == true
77
+ pair << I18n.t("common.ago.ago_word", locale: StTools.configuration.locale) if ago == true
83
78
  pair.join(' ')
84
79
  end
85
80
 
86
81
  # Метод принимает параметр - количество секунд между двумя любыми событиями в секундах,
87
82
  # и переводит их в строку на русском или иных языках вида "4 дня 23 часа назад".
88
- # Предварительно необходимо вызвать StTools.setup(:ru или :en).
83
+ # Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru (или :en) }.
89
84
  #
90
85
  # @param [DateTime] sesc количество секунд
91
86
  # @param [Boolean] ago true, если надо добавить слово "назад" в конец строки
92
87
  # @return [String] строка вида "3 дня 12 часов" или "3 дня 12 часов назад"
93
88
  # @example Примеры использования
94
- # StTools::Setup.setup(:ru)
89
+ # StTools.configure { |config| config.locale = :ru }
95
90
  # StTools::Human.seconds_ago(23, true) #=> "23 секунды назад"
96
91
  # StTools::Human.seconds_ago(24553, false) #=> 6 часов 49 минут"
97
92
  # StTools::Human.seconds_ago(0) #=> "сейчас"
98
93
  def self.seconds_ago(secs, ago = true)
99
94
  secs_i = secs.to_i
100
- return I18n.t('common.ago.just_now') if secs_i > -1 && secs_i < 1
95
+ return I18n.t('common.ago.just_now', locale: StTools.configuration.locale) if secs_i > -1 && secs_i < 1
101
96
  return '' if secs_i <= -1
102
97
  pair = self.ago_in_words_pair(secs_i)
103
- pair << I18n.t("common.ago.ago_word") if ago == true
98
+ pair << I18n.t("common.ago.ago_word", locale: StTools.configuration.locale) if ago == true
104
99
  pair.join(' ')
105
100
  end
106
101
 
107
102
  # Метод переводит DateTime в строку на русском или иных языках. Предварительно необходимо вызвать
108
- # StTools.setup(:ru или :en).
103
+ # StTools.configure { |config| config.locale = :ru (или :en) }.
104
+ #
105
+ # DEPRECATED
109
106
  #
110
107
  # @param [DateTime] time исходные время и дата
111
108
  # @param [Sym] what формат возвращаемого результата, принимает одно из следующих значений
@@ -117,7 +114,7 @@ module StTools
117
114
  # @option :short короткая форма
118
115
  # @return [String] строка с форматированными датой и временем
119
116
  # @example Примеры использования
120
- # StTools::Setup.setup(:ru)
117
+ # StTools.configure { |config| config.locale = :ru }
121
118
  # StTools::Human.format_time(Time.now, :full, :full) #=> "30 апреля 2015 г. 08:54:34"
122
119
  # StTools::Human.format_time(Time.now, :date, :full) #=> "30 апреля 2015 г."
123
120
  # StTools::Human.format_time(Time.now, :time, :full) #=> "08:54:34"
@@ -129,9 +126,57 @@ module StTools
129
126
  warn "WARNING: what ':#{what.to_s}' must be in [:full, :date, :time]. Use ':full' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
130
127
  what = :full
131
128
  end
132
- return I18n.l(time, :format => "#{what.to_s}_#{type.to_s}".to_sym)
129
+ return I18n.l(time, :format => "#{what.to_s}_#{type.to_s}".to_sym, locale: StTools.configuration.locale)
133
130
  end
134
131
 
132
+ # Метод переводит DateTime в строку на русском или иных языках. Предварительно необходимо вызвать
133
+ # StTools.configure { |config| config.locale = :ru (или :en) }.
134
+ #
135
+ # @param [DateTime] timestamp исходные время и дата
136
+ # @param [Sym] date формат возвращаемого результата, принимает одно из следующих значений
137
+ # @option :human форматирует дату и время в формате "21 марта 2011"
138
+ # @option :full форматирует дату и время в формате "21.03.2016"
139
+ # @option :short форматирует только дату в формате "21.3.16"
140
+ # @option :none игнорирует значение даты
141
+ # @param [Sym] time форма в которой возращать результат
142
+ # @option :full длинна форма в формате "08:23:03"
143
+ # @option :short короткая форма в формате "8:23", "22:34", "8:23 am"
144
+ # @option :none игнорирует значение времени
145
+ # @param [Sym] god при русской локализации и методе :human добавляет "г." после даты
146
+ # @return [String] строка с форматированными датой и временем
147
+ # @example Примеры использования
148
+ # StTools.configure { |config| config.locale = :ru }
149
+ # StTools::Human.format_time2(Time.now, :human, :full) #=> "30 апреля 2015 г. 08:54:34"
150
+ # StTools::Human.format_time2(Time.now, :human, :full, god: false) #=> "30 апреля 2015 08:54:34"
151
+ # StTools::Human.format_time2(Time.now, :human, :short) #=> "30 апреля 2015 г. 8:54"
152
+ # StTools::Human.format_time2(Time.now, :human, :none) #=> "30 апреля 2015 г."
153
+ # StTools::Human.format_time2(Time.now, :full, :full) #=> "30/04/2015 08:54:34"
154
+ # StTools::Human.format_time2(Time.now, :short, :short) #=> "30/04/15 8:54"
155
+ # StTools::Human.format_time2(Time.now, :none, :full) #=> "08:54:34"
156
+ # StTools::Human.format_time2(Time.now, :none, :short) #=> "8:54"
157
+ def self.format_time2(timestamp, date, time, god: true)
158
+ unless [:human, :full, :short, :none].include?(date)
159
+ warn "WARNING: date ':#{date.to_s}' must be in [:human, :full, :short, :none]. Use ':human' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
160
+ date = :human
161
+ end
162
+ unless [:full, :short, :none].include?(time)
163
+ warn "WARNING: time ':#{time.to_s}' must be in [:full, :short, :none]. Use ':full' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
164
+ time = :full
165
+ end
166
+
167
+ case
168
+ when date == :none && time == :none
169
+ ""
170
+ when date != :none && time == :none
171
+ StTools::Human.format_time2_date(timestamp, date, god)
172
+ when date != :none && time != :none
173
+ "#{StTools::Human.format_time2_date(timestamp, date, god)} #{StTools::Human.format_time2_time(timestamp, time)}"
174
+ when date == :none && time != :none
175
+ StTools::Human.format_time2_time(timestamp, time)
176
+ else
177
+ ""
178
+ end
179
+ end
135
180
 
136
181
  # Метод оформляет число красивым способом, в виде "1 456 742,34".
137
182
  #
@@ -193,10 +238,10 @@ module StTools
193
238
  def self.ago_in_words_one_value(val, tag)
194
239
  num100 = val % 100
195
240
  num10 = val % 10
196
- return val.to_s + " " + I18n.t("common.ago.#{tag}.other") if (num100 >=5 && num100 <= 20)
197
- return val.to_s + " " + I18n.t("common.ago.#{tag}.one") if (num10 == 1)
198
- return val.to_s + " " + I18n.t("common.ago.#{tag}.two") if ([2, 3, 4].include?(num10))
199
- return val.to_s + " " + I18n.t("common.ago.#{tag}.other")
241
+ return val.to_s + " " + I18n.t("common.ago.#{tag}.other", locale: StTools.configuration.locale) if (num100 >=5 && num100 <= 20)
242
+ return val.to_s + " " + I18n.t("common.ago.#{tag}.one", locale: StTools.configuration.locale) if (num10 == 1)
243
+ return val.to_s + " " + I18n.t("common.ago.#{tag}.two", locale: StTools.configuration.locale) if ([2, 3, 4].include?(num10))
244
+ return val.to_s + " " + I18n.t("common.ago.#{tag}.other", locale: StTools.configuration.locale)
200
245
  end
201
246
 
202
247
  def self.to_time(time, form = :local)
@@ -217,5 +262,15 @@ module StTools
217
262
  form == :utc ? time.utc : time.getlocal
218
263
  end
219
264
 
265
+ def self.format_time2_time(timestamp, format)
266
+ I18n.l(timestamp, :format => "t#{format.to_s}".to_sym, locale: StTools.configuration.locale)
267
+ end
268
+
269
+ def self.format_time2_date(timestamp, format, god)
270
+ res = I18n.l(timestamp, :format => "d#{format.to_s}".to_sym, locale: StTools.configuration.locale)
271
+ res += " г." if god && StTools.configuration.locale == :ru
272
+ res
273
+ end
274
+
220
275
  end
221
276
  end
@@ -16,8 +16,7 @@ module StTools
16
16
  'ъ' => '', 'ю' => 'ju', 'я' => 'ja',
17
17
  'Ж' => 'Zh', 'Ц' => 'Ts', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch',
18
18
  'Ъ' => '', 'Ю' => 'Ju', 'Я' => 'Ja')
19
- translited.gsub!('\'', '')
20
- return translited
19
+ translited.gsub('\'', '')
21
20
  end
22
21
 
23
22
  # Метод преобразует строку в нижний регистр с одновременной заменой буквы 'ё' на 'е'.
@@ -29,9 +28,15 @@ module StTools
29
28
  # @example Примеры использования
30
29
  # StTools::String.downcase("Hello, Вася!") #=> "hello, вася!"
31
30
  def self.downcase(text)
32
- return nil if text.nil?
33
- return text.tr('QWERTYUIOPASDFGHJKLZXCVBNMАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',
34
- 'qwertyuiopasdfghjklzxcvbnmабвгдеёжзийклмнопрстуфхцчшщъыьэюя').gsub('ё', 'е')
31
+ if text
32
+ if RUBY_VERSION < "2.4"
33
+ return text.tr('QWERTYUIOPASDFGHJKLZXCVBNMАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',
34
+ 'qwertyuiopasdfghjklzxcvbnmабвгдеежзийклмнопрстуфхцчшщъыьэюя')
35
+ else
36
+ return text.downcase
37
+ end
38
+ end
39
+ ""
35
40
  end
36
41
 
37
42
  # Метод преобразует строку в верхний регистр с одновременной заменой буквы 'Ё' на 'Е'.
@@ -43,9 +48,15 @@ module StTools
43
48
  # @example Примеры использования
44
49
  # StTools::String.upcase("Hello, Вася!") #=> "HELLO, ВАСЯ!"
45
50
  def self.upcase(text)
46
- return nil if text.nil?
47
- return text.tr('qwertyuiopasdfghjklzxcvbnmабвгдеёжзийклмнопрстуфхцчшщъыьэюя',
48
- 'QWERTYUIOPASDFGHJKLZXCVBNMАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ').gsub('Ё', 'Е')
51
+ if text
52
+ if RUBY_VERSION < "2.4"
53
+ return text.tr('qwertyuiopasdfghjklzxcvbnmабвгдеёжзийклмнопрстуфхцчшщъыьэюя',
54
+ 'QWERTYUIOPASDFGHJKLZXCVBNMАБВГДЕЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ')
55
+ else
56
+ return text.upcase
57
+ end
58
+ end
59
+ ""
49
60
  end
50
61
 
51
62
  # Метод заменяет в исходной строке английские символы, похожие
@@ -57,7 +68,7 @@ module StTools
57
68
  # @return [String] текст только с русскими буквами
58
69
  def self.delat(text)
59
70
  return nil if text.nil?
60
- return text.tr('ёЁEeHCcTOoPpAHKXxBM', 'еЕЕеНСсТОоРрАНКХхВМ')
71
+ text.tr('ёЁEeHCcTOoPpAHKXxBM', 'еЕЕеНСсТОоРрАНКХхВМ')
61
72
  end
62
73
 
63
74
  # Метод проводит нормализацию строки для последующей машиной обработки. При этом осуществляется:
@@ -68,12 +79,16 @@ module StTools
68
79
  # - в строке удаляются повторные пробелы между словами
69
80
  #
70
81
  # @param [String] text строка, введенная пользователям
82
+ # @param [Boolean] delat флаг необходимости проводить де-латинизацию. По умолчанию - false
71
83
  # @return [String] строка без 'ё', в нижнем регистре, без английских букв
72
84
  # @example Примеры использования
73
85
  # StTools::String.normalize(" Ёлки- ПАЛКИ") #=> "елки- палки"
74
- def self.normalize(text)
75
- return nil if text.nil?
76
- return self.downcase(self.delat(text)).strip.gsub(/[\s\t\u00A0]{1,100}/, ' ')
86
+ # StTools::String.normalize("Ee", delat: true) #=> "ее" (русские буквы)
87
+ # StTools::String.normalize("Ee") #=> "ee" (латинские буквы)
88
+ def self.normalize(text, delat: false)
89
+ return nil if text.nil? || text.empty?
90
+ out = delat ? self.delat(text) : text.gsub('ё', 'е').gsub('Ё', 'Е')
91
+ self.downcase(out).strip.gsub(/[\s\t\u00A0]{1,100}/, ' ')
77
92
  end
78
93
 
79
94
  # Метод позволяет показывать клиенту строку в неполном объеме, с закрытием части символов в строке звездочкой.
@@ -91,7 +106,7 @@ module StTools
91
106
  len = text.length - 3
92
107
  0.upto((len/4).to_i) do
93
108
  pos = rand(len)
94
- text[pos,1] = '*'
109
+ text[pos, 1] = '*'
95
110
  end
96
111
  return text
97
112
  end
@@ -218,7 +233,7 @@ module StTools
218
233
  #
219
234
  # @return [String] конвертированная строка
220
235
  # @example Примеры использования
221
- # StTools::Setup.setup(:ru)
236
+ # StTools.configure { |config| config.locale = :ru }
222
237
  # StTools::String.pretty_list([1,2]) #=> "1 и 2"
223
238
  # StTools::String.pretty_list([1,2,4]) #=> "1, 2 и 4"
224
239
  # StTools::String.pretty_list([1,2,3,4], union: :or) #=> "1, 2, 3 или 4"
@@ -227,7 +242,7 @@ module StTools
227
242
  return "#{pretag}#{items.first}#{afttag}" if items.count == 1
228
243
  out = Array.new
229
244
  last = items.last
230
- arr = items[0,items.count-1]
245
+ arr = items[0, items.count-1]
231
246
  arr.each do |one|
232
247
  out << "#{pretag}#{one}#{afttag}"
233
248
  out << separator + ' '
@@ -235,9 +250,9 @@ module StTools
235
250
  out.pop
236
251
  case union
237
252
  when :and
238
- out << " #{I18n.t('string.pretty_list.and')} "
253
+ out << " #{I18n.t('st_tools.pretty_list.and', locale: StTools.configuration.locale)} "
239
254
  else
240
- out << " #{I18n.t('string.pretty_list.or')} "
255
+ out << " #{I18n.t('st_tools.pretty_list.or', locale: StTools.configuration.locale)} "
241
256
  end
242
257
  out << "#{pretag}#{last}#{afttag}"
243
258
  out.join
@@ -261,7 +276,7 @@ module StTools
261
276
  return text if text.length <= length
262
277
  return text[0, length] if length <= endwith.length
263
278
 
264
- out = text.strip[0,length - endwith.length]
279
+ out = text.strip[0, length - endwith.length]
265
280
  out.gsub!(/\s[^\s]+?\z/, '') if words
266
281
  out.strip + endwith
267
282
  end
@@ -1,3 +1,3 @@
1
1
  module StTools
2
- VERSION = '0.3.18'
2
+ VERSION = '0.4.0'
3
3
  end
@@ -0,0 +1,30 @@
1
+ require "st_tools"
2
+
3
+ input = "Слово о полку ИГОРЕВЕ (Slovo O POLKU IGOREVE)"
4
+ count = 50_000
5
+ total = 5
6
+
7
+ def test_st_tools(str, count)
8
+ started_at = Time.now.to_f
9
+ count.times do
10
+ StTools::String.downcase(str)
11
+ end
12
+ executed_at = Time.now.to_f - started_at
13
+ speed = count.to_f / executed_at
14
+ puts "Executed at: #{executed_at.round(3)} sec (speed = #{speed.round(1)} ops/sec)"
15
+ speed
16
+ end
17
+
18
+ puts "RUBY_VERSION: #{RUBY_VERSION}"
19
+
20
+ avg = 0
21
+ puts "StTools::Strings.downcase"
22
+ total.times do
23
+ avg += test_st_tools(input, count)
24
+ end
25
+ puts "------------------------------------------------------"
26
+ puts "Average speed = #{(avg.to_f / total).round(1)} ops/sec"
27
+ puts
28
+
29
+
30
+
@@ -0,0 +1,58 @@
1
+ require 'rspec'
2
+ require 'st_tools'
3
+
4
+ describe 'Проверка методов StTools::Human.format_time2 (:ru)' do
5
+ it '.format_time2 (:human, :full)' do
6
+ StTools.configure { |config| config.locale = :ru }
7
+ test = ::StTools::Human.format_time2(Time.now, :human, :full)
8
+ expect(test).to match(/[а-я]{3,10}/)
9
+ expect(test).to match(/г\./)
10
+ expect(test).to match(/\d{2}\:\d{2}\:\d{2}/)
11
+ end
12
+
13
+ it '.format_time2 (:human, :full, god:false)' do
14
+ StTools.configure { |config| config.locale = :ru }
15
+ test = ::StTools::Human.format_time2(Time.now, :human, :full, god: false)
16
+ expect(test).to match(/[а-я]{3,10}/)
17
+ expect(test).to_not match(/г\./)
18
+ expect(test).to match(/\d{2}\:\d{2}\:\d{2}/)
19
+ end
20
+
21
+ it '.format_time2 (:full, :full)' do
22
+ StTools.configure { |config| config.locale = :ru }
23
+ test = ::StTools::Human.format_time2(Time.now, :full, :full)
24
+ expect(test).to match(/\d{2}\/\d{2}\/\d{4}/)
25
+ expect(test).to match(/\d{2}\:\d{2}\:\d{2}/)
26
+ end
27
+
28
+ it '.format_time2 (:full, :short)' do
29
+ StTools.configure { |config| config.locale = :ru }
30
+ test = ::StTools::Human.format_time2(Time.now, :full, :short)
31
+ expect(test).to match(/\d{2}\/\d{2}\/\d{4}/)
32
+ expect(test).to_not match(/\d{2}\:\d{2}\:\d{2}/)
33
+ end
34
+ end
35
+
36
+ describe 'Проверка методов StTools::Human.format_time2 (:en)' do
37
+ it '.format_time2 (:human, :full)' do
38
+ StTools.configure { |config| config.locale = :en }
39
+ test = ::StTools::Human.format_time2(Time.now, :human, :full)
40
+ expect(test).to match(/[a-zA-Z]{3,10}/)
41
+ expect(test).to match(/\d{2}\:\d{2}\:\d{2}/)
42
+ end
43
+
44
+ it '.format_time2 (:full, :full)' do
45
+ StTools.configure { |config| config.locale = :en }
46
+ test = ::StTools::Human.format_time2(Time.now, :full, :full)
47
+ expect(test).to match(/\d{2}\/\d{2}\/\d{4}/)
48
+ expect(test).to match(/\d{2}\:\d{2}\:\d{2}/)
49
+ end
50
+
51
+ it '.format_time2 (:full, :short)' do
52
+ StTools.configure { |config| config.locale = :en }
53
+ test = ::StTools::Human.format_time2(Time.now, :full, :short)
54
+ expect(test).to match(/\d{2}\/\d{2}\/\d{4}/)
55
+ expect(test).to_not match(/\d{2}\:\d{2}\:\d{2}/)
56
+ end
57
+ end
58
+
@@ -4,63 +4,94 @@ require 'st_tools'
4
4
 
5
5
  describe 'Проверка методов StTools::Human.*' do
6
6
  it '.bytes(234)' do
7
+ StTools.configure { |config| config.locale = :ru }
7
8
  test = ::StTools::Human.bytes(234)
8
9
  expect(test).to include('234')
9
10
  expect(test).to include('байт')
10
11
  end
11
12
 
12
13
  it '.bytes(14234)' do
14
+ StTools.configure { |config| config.locale = :ru }
13
15
  test = ::StTools::Human.bytes(14234)
14
16
  expect(test).to include('14')
15
17
  expect(test).to include('кбайт')
16
18
  end
17
19
 
20
+ it '.bytes(:en, 234)' do
21
+ StTools.configure { |config| config.locale = :en }
22
+ test = ::StTools::Human.bytes(234)
23
+ expect(test).to include('234')
24
+ expect(test).to include('b')
25
+ end
26
+
27
+ it '.bytes(:en, 14234)' do
28
+ StTools.configure { |config| config.locale = :en }
29
+ test = ::StTools::Human.bytes(14234)
30
+ expect(test).to include('14')
31
+ expect(test).to include('kb')
32
+ end
33
+
18
34
  it '.number(234)' do
35
+ StTools.configure { |config| config.locale = :ru }
19
36
  test = ::StTools::Human.number(234)
20
37
  expect(test).to include('234')
21
38
  end
22
39
 
23
40
  it '.number(14234)' do
41
+ StTools.configure { |config| config.locale = :ru }
24
42
  test = ::StTools::Human.number(14234)
25
43
  expect(test).to include('14')
26
- expect(test).to include('тыс.')
44
+ expect(test).to include(' тыс.')
45
+ end
46
+
47
+ it '.number(:en, 234)' do
48
+ StTools.configure { |config| config.locale = :en }
49
+ test = ::StTools::Human.number(234)
50
+ expect(test).to include('234')
51
+ end
52
+
53
+ it '.number(:en, 14234)' do
54
+ StTools.configure { |config| config.locale = :en }
55
+ test = ::StTools::Human.number(14234)
56
+ expect(test).to include('14k')
27
57
  end
28
58
 
29
59
  it '.memory' do
60
+ StTools.configure { |config| config.locale = :ru }
30
61
  test = ::StTools::Human.memory
31
62
  expect(test).to include('байт')
32
63
  end
33
64
 
34
65
  it '.human_ago (:ru)' do
35
- ::StTools::Setup.setup(:ru)
66
+ StTools.configure { |config| config.locale = :ru }
36
67
  test = ::StTools::Human.human_ago(DateTime.new(2001,2,3,4,5,6,'+7'), true)
37
68
  expect(test).to include('назад')
38
69
  expect(test).to include('лет')
39
70
  end
40
71
 
41
72
  it '.human_ago (:en)' do
42
- ::StTools::Setup.setup(:en)
73
+ StTools.configure { |config| config.locale = :en }
43
74
  test = ::StTools::Human.human_ago(DateTime.new(2001,2,3,4,5,6,'+7'), true)
44
75
  expect(test).to include('ago')
45
76
  expect(test).to include('years')
46
77
  end
47
78
 
48
79
  it '.seconds_ago (:ru)' do
49
- ::StTools::Setup.setup(:ru)
80
+ StTools.configure { |config| config.locale = :ru }
50
81
  test = ::StTools::Human.seconds_ago(67, true)
51
82
  expect(test).to include('назад')
52
83
  expect(test).to include('1 минута')
53
84
  end
54
85
 
55
86
  it '.seconds_ago (:en)' do
56
- ::StTools::Setup.setup(:en)
87
+ StTools.configure { |config| config.locale = :en }
57
88
  test = ::StTools::Human.seconds_ago(67, true)
58
89
  expect(test).to include('ago')
59
90
  expect(test).to include('1 minute')
60
91
  end
61
92
 
62
93
  it '.format_time (:ru)' do
63
- ::StTools::Setup.setup(:ru)
94
+ StTools.configure { |config| config.locale = :ru }
64
95
  test = ::StTools::Human.format_time(Time.now, :full, :full)
65
96
  expect(test).to match(/[а-я]{1,3}/)
66
97
  test = ::StTools::Human.format_time(Time.now, :full, :short)
@@ -68,7 +99,7 @@ describe 'Проверка методов StTools::Human.*' do
68
99
  end
69
100
 
70
101
  it '.format_time (:en)' do
71
- ::StTools::Setup.setup(:en)
102
+ StTools.configure { |config| config.locale = :en }
72
103
  test = ::StTools::Human.format_time(Time.now, :full, :full)
73
104
  expect(test).to match(/[a-z]{1,3}/i)
74
105
  test = ::StTools::Human.format_time(Time.now, :full, :short)
@@ -95,5 +126,5 @@ describe 'Проверка методов StTools::Human.*' do
95
126
  expect(test).to match('0')
96
127
  end
97
128
 
129
+ end
98
130
 
99
- end
@@ -14,10 +14,20 @@ describe 'Проверка методов StTools::String.*' do
14
14
  end
15
15
 
16
16
  it '.normalize' do
17
- test = ::StTools::String.normalize('Ярослав Му(y)дрёный')
17
+ test = ::StTools::String.normalize('Ярослав Му(y)дрёный', delat: true)
18
18
  expect(test).to include('ярослав му(y)дреный')
19
19
  end
20
20
 
21
+ it '.normalize без delat' do
22
+ test = ::StTools::String.normalize('Ee') # Английские буквы
23
+ expect(test).to include('ee') # Английские буквы
24
+ end
25
+
26
+ it '.normalize с delat' do
27
+ test = ::StTools::String.normalize('Ee', delat: true) # Английкие буквы
28
+ expect(test).to include('ее') # Русские буквы
29
+ end
30
+
21
31
  it '.downcase("EngLish")' do
22
32
  test = ::StTools::String.downcase('EngLish')
23
33
  expect(test).to include('english')
@@ -112,7 +122,7 @@ describe 'Проверка методов StTools::String.*' do
112
122
  end
113
123
 
114
124
  it 'pretty_list - ru' do
115
- ::StTools::Setup.setup(:ru)
125
+ StTools.configure { |config| config.locale = :ru }
116
126
  test = ::StTools::String.pretty_list(['Паша'])
117
127
  expect(test).to eq('Паша')
118
128
  test = ::StTools::String.pretty_list(['Паша', 'Маша'])
@@ -126,7 +136,7 @@ describe 'Проверка методов StTools::String.*' do
126
136
  end
127
137
 
128
138
  it 'pretty_list - en' do
129
- ::StTools::Setup.setup(:en)
139
+ StTools.configure { |config| config.locale = :en }
130
140
  test = ::StTools::String.pretty_list(['Паша'])
131
141
  expect(test).to eq('Паша')
132
142
  test = ::StTools::String.pretty_list(['Паша', 'Маша'])
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: st_tools
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.18
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stan Zhuravlev
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2016-05-12 00:00:00.000000000 Z
11
+ date: 2016-09-10 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -98,8 +98,10 @@ files:
98
98
  - lib/st_tools/system.rb
99
99
  - lib/st_tools/tokenizer.rb
100
100
  - lib/st_tools/version.rb
101
+ - test/bench/strings/downcase.rb
101
102
  - test/countries_lib_spec.rb
102
103
  - test/fias_lib_spec.rb
104
+ - test/human_lib_format_time2_spec.rb
103
105
  - test/human_lib_spec.rb
104
106
  - test/progress_bar_lib_spec.rb
105
107
  - test/string_caps_lib_spec.rb