Method: Duration#format
- Defined in:
- lib/duration.rb
#format(format_str) ⇒ Object Also known as: strftime
Format a duration into a human-readable string.
%w => weeks
%d => days
%h => hours
%m => minutes
%s => seconds
%td => total days
%th => total hours
%tm => total minutes
%ts => total seconds
%t => total seconds
%MP => minutes with UTF-8 prime
%SP => seconds with UTF-8 double-prime
%MH => minutes with HTML prime
%SH => seconds with HTML double-prime
%H => zero-padded hours
%M => zero-padded minutes
%S => zero-padded seconds
%~s => locale-dependent "seconds" terminology
%~m => locale-dependent "minutes" terminology
%~h => locale-dependent "hours" terminology
%~d => locale-dependent "days" terminology
%~w => locale-dependent "weeks" terminology
%tdu => total days with locale-dependent unit
%thu => total hours with locale-dependent unit
%tmu => total minutes with locale-dependent unit
%tsu => total seconds with locale-dependent unit
You can also use the I18n support. The %~s, %~m, %~h, %~d and %~w can be translated with I18n. If you are using Ruby on Rails, the support is ready out of the box, so just change your locale file. Otherwise you can try:
I18n.load_path << "path/to/your/locale"
I18n.locale = :your_locale
And you must use the following structure (example) for your locale file:
pt:
ruby_duration:
second: segundo
seconds: segundos
minute: minuto
minutes: minutos
hour: hora
hours: horas
day: dia
days: dias
week: semana
weeks: semanas
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/duration.rb', line 175 def format(format_str) identifiers = { 'w' => @weeks, 'd' => @days, 'h' => @hours, 'm' => @minutes, 's' => @seconds, 'td' => Proc.new { total_days }, 'th' => Proc.new { total_hours }, 'tm' => Proc.new { total_minutes }, 'ts' => @total, 't' => @total, 'MP' => Proc.new { "#{@minutes}′"}, 'SP' => Proc.new { "#{@seconds}″"}, 'MH' => Proc.new { "#{@minutes}′"}, 'SH' => Proc.new { "#{@seconds}″"}, 'H' => @hours.to_s.rjust(2, '0'), 'M' => @minutes.to_s.rjust(2, '0'), 'S' => @seconds.to_s.rjust(2, '0'), '~s' => i18n_for(:second), '~m' => i18n_for(:minute), '~h' => i18n_for(:hour), '~d' => i18n_for(:day), '~w' => i18n_for(:week), 'tdu'=> Proc.new { "#{total_days} #{i18n_for(:total_day)}"}, 'thu'=> Proc.new { "#{total_hours} #{i18n_for(:total_hour)}"}, 'tmu'=> Proc.new { "#{total_minutes} #{i18n_for(:total_minute)}"}, 'tsu'=> Proc.new { "#{total} #{i18n_for(:total)}"}, } format_str.gsub(/%?%(w|d|h|m|s|t([dhms]u?)?|MP|SP|MH|SH|H|M|S|~(?:s|m|h|d|w))/) do |match| match['%%'] ? match : (identifiers[match[1..-1]].class == Proc ? identifiers[match[1..-1]].call : identifiers[match[1..-1]]) end.gsub('%%', '%') end |