Class: StTools::Human

Inherits:
Object
  • Object
show all
Defined in:
lib/st_tools/human.rb

Class Method Summary collapse

Class Method Details

.bytes(val) ⇒ String

Метод форматирует число, добавляя суффиксы ‘кбайт’, ‘Мбайт’ и др. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.bytes(123)           #=> "123 байта"
StTools::Human.bytes(14563)         #=> "14 кбайт"
StTools::Human.bytes(763552638)     #=> "728.2 Мбайт"

Parameters:

  • val (Integer)

    исходное числовое значение в байтах

Returns:

  • (String)

    строка вида “512,4 Мбайт”



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/st_tools/human.rb', line 37

def self.bytes(val)
  # noinspection RubyStringKeysInHashInspection
  StTools.configuration.bytes_array.each_pair do |e, s|
    if val < s
      if s <= 1024*1024
        return "#{(val.to_f / (s / 1024)).round(0)} #{e}"
      else
        return "#{(val.to_f / (s / 1024)).round(1)} #{e}"
      end
    end
  end
end

.format_time(time, what, type) ⇒ String

Метод переводит DateTime в строку на русском или иных языках. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru (или :en) }.

DEPRECATED

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.format_time(Time.now, :full, :full)       #=> "30 апреля 2015 г. 08:54:34"
StTools::Human.format_time(Time.now, :date, :full)       #=> "30 апреля 2015 г."
StTools::Human.format_time(Time.now, :time, :full)       #=> "08:54:34"
StTools::Human.format_time(Time.now, :full, :short)      #=> "30/04/2015 08:55"
StTools::Human.format_time(Time.now, :date, :short)      #=> "30/04/2015"
StTools::Human.format_time(Time.now, :time, :short)      #=> "08:55"

Parameters:

  • time (DateTime)

    исходные время и дата

  • what (Sym)

    формат возвращаемого результата, принимает одно из следующих значений

  • type (Sym)

    форма в которой возращать результат: длинная (“28 апреля 2015 г. 10:34:52”) или короткая (“28/04/2015 10:34”)

  • :full (Hash)

    a customizable set of options

  • :date (Hash)

    a customizable set of options

  • :time (Hash)

    a customizable set of options

  • :short (Hash)

    a customizable set of options

Returns:

  • (String)

    строка с форматированными датой и временем



124
125
126
127
128
129
130
# File 'lib/st_tools/human.rb', line 124

def self.format_time(time, what, type)
  unless [:full, :date, :time].include?(what)
    warn "WARNING: what ':#{what.to_s}' must be in [:full, :date, :time]. Use ':full' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
    what = :full
  end
  return I18n.l(time, :format => "#{what.to_s}_#{type.to_s}".to_sym, locale: StTools.configuration.locale)
end

.format_time2(timestamp, date, time, god: true) ⇒ String

Метод переводит DateTime в строку на русском или иных языках. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru (или :en) }.

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.format_time2(Time.now, :human, :full)               #=> "30 апреля 2015 г. 08:54:34"
StTools::Human.format_time2(Time.now, :human, :full, god: false)   #=> "30 апреля 2015 08:54:34"
StTools::Human.format_time2(Time.now, :human, :short)              #=> "30 апреля 2015 г. 8:54"
StTools::Human.format_time2(Time.now, :human, :none)               #=> "30 апреля 2015 г."
StTools::Human.format_time2(Time.now, :full, :full)                #=> "30/04/2015 08:54:34"
StTools::Human.format_time2(Time.now, :short, :short)              #=> "30/04/15 8:54"
StTools::Human.format_time2(Time.now, :none, :full)                #=> "08:54:34"
StTools::Human.format_time2(Time.now, :none, :short)               #=> "8:54"

Parameters:

  • timestamp (DateTime)

    исходные время и дата

  • date (Sym)

    формат возвращаемого результата, принимает одно из следующих значений

  • time (Sym)

    форма в которой возращать результат

  • god (Sym) (defaults to: true)

    при русской локализации и методе :human добавляет “г.” после даты

  • :human (Hash)

    a customizable set of options

  • :full (Hash)

    a customizable set of options

  • :short (Hash)

    a customizable set of options

  • :none (Hash)

    a customizable set of options

Returns:

  • (String)

    строка с форматированными датой и временем



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/st_tools/human.rb', line 157

def self.format_time2(timestamp, date, time, god: true)
  unless [:human, :full, :short, :none].include?(date)
    warn "WARNING: date ':#{date.to_s}' must be in [:human, :full, :short, :none]. Use ':human' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
    date = :human
  end
  unless [:full, :short, :none].include?(time)
    warn "WARNING: time ':#{time.to_s}' must be in [:full, :short, :none]. Use ':full' now (at line #{__LINE__} of StTools::#{File.basename(__FILE__)})"
    time = :full
  end

  case
    when date == :none && time == :none
      ""
    when date != :none && time == :none
      StTools::Human.format_time2_date(timestamp, date, god)
    when date != :none && time != :none
      "#{StTools::Human.format_time2_date(timestamp, date, god)} #{StTools::Human.format_time2_time(timestamp, time)}"
    when date == :none && time != :none
      StTools::Human.format_time2_time(timestamp, time)
    else
      ""
  end
end

.human_ago(time, ago = true) ⇒ String

Метод переводит DateTime в строку на русском или иных языках вида “4 дня 23 часа назад”. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.human_ago(Time.now - 23, true)       #=> "23 секунды назад"
StTools::Human.human_ago(Time.now - 24553, false)   #=> 6 часов 49 минут"
StTools::Human.human_ago(Time.now)                  #=> "сейчас"

Parameters:

  • time (DateTime)

    время и дата

  • ago (Boolean) (defaults to: true)

    true, если надо добавить слово “назад” в конец строки

Returns:

  • (String)

    строка вида “3 дня 12 часов” или “3 дня 12 часов назад”



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/st_tools/human.rb', line 69

def self.human_ago(time, ago = true)
  now = self.to_time(Time.now.strftime('%Y-%m-%d %H:%M:%S UTC'))
  slf = self.to_time(time.strftime('%Y-%m-%d %H:%M:%S UTC'))
  secs = (now - slf).to_i
  return I18n.t('common.ago.very_long', locale: StTools.configuration.locale) if time.year < 1800
  return I18n.t('common.ago.just_now', locale: StTools.configuration.locale) if secs > -1 && secs < 1
  return '' if secs <= -1
  pair = self.ago_in_words_pair(secs)
  pair << I18n.t("common.ago.ago_word", locale: StTools.configuration.locale) if ago == true
  pair.join(' ')
end

.memoryString

Метод возвращает форматированную строку с объемом памяти, занимаемым текущим процессом (pid).

Returns:

  • (String)

    строка вида “512,4 Мбайт”



53
54
55
56
# File 'lib/st_tools/human.rb', line 53

def self.memory
  val = ::StTools::System.memory
  return self.bytes(val)
end

.number(val) ⇒ String

Метод форматирует число, добавляя суффиксы ‘тыс.’, ‘млн.’ и пр. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru }.

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.number(123)           #=> "123"
StTools::Human.number(14563)         #=> "14 тыс."
StTools::Human.number(763552638)     #=> "763.6 млн."

Parameters:

  • val (Integer)

    исходное числовое значение

Returns:

  • (String)

    строка вида “512,4 тыс.”



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/st_tools/human.rb', line 15

def self.number(val)
  StTools.configuration.numbers_array.each_pair do |e, s|
    if val < s
      if s <= 1000*1000
        return "#{(val.to_f / (s / 1000)).round(0)}#{I18n.t('st_tools.numbers_separator', locale: StTools.configuration.locale)}#{e}"
      else
        return "#{(val.to_f / (s / 1000)).round(1)}#{I18n.t('st_tools.numbers_separator', locale: StTools.configuration.locale)}#{e}"
      end
    end
  end
end

.pretty_number(value, round: 0, nobr: false, strong: false) ⇒ String

Метод оформляет число красивым способом, в виде “1 456 742,34”.

Examples:

Примеры использования

StTools::Human.pretty_number(345)                       # => 345
StTools::Human.pretty_number(345, round: 2)             # => 345,00
StTools::Human.pretty_number(75345, round: 1)           # => 75 345,0
StTools::Human.pretty_number(nil)                       # => 0
StTools::Human.pretty_number('1675345.763', round: 1)   # => 1 675 345,7

Parameters:

  • value (Object)

    исходное число в виде строки или числа, допустим nil

  • round (Integer) (defaults to: 0)

    число цифр после запятой (по умолчанию - 0)

  • nobr (Boolean) (defaults to: false)

    обрамить результат тегами nobr (по умолчанию - false)

  • strong (Boolean) (defaults to: false)

    обрамить результат тегами strong (по умолчанию - false)

Returns:

  • (String)

    строка с форматированным числом



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/st_tools/human.rb', line 194

def self.pretty_number(value, round: 0, nobr: false, strong: false)
  out = StTools::String.to_float(value, round: round, stop: false).to_s
  arr = out.split(/[\,\.]/)
  tmp = arr.first.split(//).reverse.each_slice(3).to_a
  out = Array.new
  tmp.each do |one|
    out << one.reverse.join
  end
  out = out.reverse.join(' ')
  if arr.count > 1
    out = [out, (arr.last + '000000000000000')[0,round]].join(',')
  end
  out = "<nobr>#{out}</nobr>" if nobr
  out = "<strong>#{out}</strong>" if strong
  out
end

.seconds_ago(secs, ago = true) ⇒ String

Метод принимает параметр - количество секунд между двумя любыми событиями в секундах, и переводит их в строку на русском или иных языках вида “4 дня 23 часа назад”. Предварительно необходимо вызвать StTools.configure { |config| config.locale = :ru (или :en) }.

Examples:

Примеры использования

StTools.configure { |config| config.locale = :ru }
StTools::Human.seconds_ago(23, true)       #=> "23 секунды назад"
StTools::Human.seconds_ago(24553, false)   #=> 6 часов 49 минут"
StTools::Human.seconds_ago(0)              #=> "сейчас"

Parameters:

  • sesc (DateTime)

    количество секунд

  • ago (Boolean) (defaults to: true)

    true, если надо добавить слово “назад” в конец строки

Returns:

  • (String)

    строка вида “3 дня 12 часов” или “3 дня 12 часов назад”



93
94
95
96
97
98
99
100
# File 'lib/st_tools/human.rb', line 93

def self.seconds_ago(secs, ago = true)
  secs_i = secs.to_i
  return I18n.t('common.ago.just_now', locale: StTools.configuration.locale) if secs_i > -1 && secs_i < 1
  return '' if secs_i <= -1
  pair = self.ago_in_words_pair(secs_i)
  pair << I18n.t("common.ago.ago_word", locale: StTools.configuration.locale) if ago == true
  pair.join(' ')
end