Module: SimpleFormatter
- Defined in:
- lib/simple_formatter.rb
Class Method Summary collapse
- .camelize(str) ⇒ Object
- .duration(seconds) ⇒ Object
- .number(n, delimiter: ',', separator: '.') ⇒ Object
- .slugify(str) ⇒ Object
- .table(rows, headers: nil) ⇒ Object
- .truncate(str, max_len, suffix: '...') ⇒ Object
- .underscore(str) ⇒ Object
Class Method Details
.camelize(str) ⇒ Object
37 38 39 |
# File 'lib/simple_formatter.rb', line 37 def self.camelize(str) str.to_s.split(/[_\-\s]+/).map(&:capitalize).join end |
.duration(seconds) ⇒ Object
66 67 68 69 70 71 |
# File 'lib/simple_formatter.rb', line 66 def self.duration(seconds) h = seconds / 3600 m = (seconds % 3600) / 60 s = seconds % 60 format('%02d:%02d:%02d', h, m, s) end |
.number(n, delimiter: ',', separator: '.') ⇒ Object
47 48 49 50 51 |
# File 'lib/simple_formatter.rb', line 47 def self.number(n, delimiter: ',', separator: '.') parts = n.to_s.split('.') parts[0] = parts[0].reverse.scan(/.{1,3}/).join(delimiter).reverse parts.join(separator) end |
.slugify(str) ⇒ Object
33 34 35 |
# File 'lib/simple_formatter.rb', line 33 def self.slugify(str) str.to_s.downcase.strip.gsub(/[^\w\s-]/, '').gsub(/[\s_-]+/, '-').gsub(/^-+|-+$/, '') end |
.table(rows, headers: nil) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/simple_formatter.rb', line 53 def self.table(rows, headers: nil) all = headers ? [headers] + rows : rows widths = (0...all.first.length).map { |i| all.map { |r| r[i].to_s.length }.max } line = '+' + widths.map { |w| '-' * (w + 2) }.join('+') + '+' result = [line] all.each_with_index do |row, idx| result << '| ' + row.each_with_index.map { |cell, i| cell.to_s.ljust(widths[i]) }.join(' | ') + ' |' result << line if idx == 0 && headers end result << line result.join("\n") end |
.truncate(str, max_len, suffix: '...') ⇒ Object
28 29 30 31 |
# File 'lib/simple_formatter.rb', line 28 def self.truncate(str, max_len, suffix: '...') str = str.to_s str.length <= max_len ? str : str[0, max_len - suffix.length] + suffix end |
.underscore(str) ⇒ Object
41 42 43 44 45 |
# File 'lib/simple_formatter.rb', line 41 def self.underscore(str) str.to_s.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end |