Module: RQRCode::Export::ANSI

Defined in:
lib/rqrcode/export/ansi.rb

Instance Method Summary collapse

Instance Method Details

#as_ansi(options = {}) ⇒ Object

Returns a string of the QR code as characters writen with ANSI background set.

Options: light: Foreground (“033[47m”) dark: Background ANSI code. (“033[40m”) fill_character: The written character. (‘ ’) quiet_zone_size: (4)



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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rqrcode/export/ansi.rb', line 16

def as_ansi(options = {})
  options = {
    light: "\033[47m",
    dark: "\033[40m",
    fill_character: "  ",
    quiet_zone_size: 4
  }.merge(options)

  normal = "\033[m\n"
  light = options.fetch(:light)
  dark = options.fetch(:dark)
  fill_character = options.fetch(:fill_character)
  quiet_zone_size = options.fetch(:quiet_zone_size)
  output = []

  @qrcode.modules.each_index do |c|
    # start row with quiet zone
    row = light + fill_character * quiet_zone_size
    previous_dark = false

    @qrcode.modules.each_index do |r|
      if @qrcode.checked?(c, r)
        if previous_dark != true
          row << dark
          previous_dark = true
        end
      elsif previous_dark != false
        # light
        row << light
        previous_dark = false
      end

      row << fill_character
    end

    # add quiet zone
    if previous_dark != false
      row << light
    end
    row << fill_character * quiet_zone_size

    # always end with reset and newline
    row << normal

    output << row
  end

  # count the row width so we can add quiet zone rows
  width = output.first.scan(fill_character).length

  quiet_row = light + fill_character * width + normal
  quiet_rows = quiet_row * quiet_zone_size

  quiet_rows + output.join + quiet_rows
end