File: pt.rb

package info (click to toggle)
ruby-humanize 2.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,108 kB
  • sloc: ruby: 1,779; makefile: 7; sh: 1
file content (49 lines) | stat: -rw-r--r-- 1,104 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require_relative 'constants/pt'

module Humanize
  class Pt
    def humanize(number)
      iteration = 0
      parts = []
      use_and = false
      until number.zero?
        number, remainder = number.divmod(1000)
        plural = remainder > 1
        unless remainder.zero?
          if iteration.zero? && remainder < 100
            use_and = true
          else
            add_grouping(parts, use_and, iteration, plural)
          end

          parts << SUB_ONE_GROUPING[remainder] unless one_thousand?(remainder, parts)
        end

        iteration += 1
      end

      parts
    end

    private

    def one_thousand?(remainder, parts)
      remainder == 1 && (parts.last.to_s.strip == 'mil' || parts.last.to_s.strip == 'mil e')
    end

    def conjunction(parts, use_and)
      return '' if parts.empty?

      use_and ? ' e' : ', '
    end

    def add_grouping(parts, use_and, iteration, plural)
      grouping = LOTS[iteration]
      return unless grouping

      grouping.sub! 'lhão', 'lhões' if plural

      parts << "#{grouping}#{conjunction(parts, use_and)}"
    end
  end
end