Class: QRCode::Encoder::NumericSegment

Inherits:
Segment
  • Object
show all
Defined in:
lib/qrcode/encoder/segment.rb

Overview

Numeric segment - optimized for numeric data (0-9)

Instance Attribute Summary

Attributes inherited from Segment

#data

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Segment

#bit_size, build, #header_size

Constructor Details

#initialize(data) ⇒ NumericSegment

Returns a new instance of NumericSegment.



101
102
103
104
105
106
107
# File 'lib/qrcode/encoder/segment.rb', line 101

def initialize(data)
  data_str = data.to_s
  unless self.class.valid_data?(data_str)
    raise ArgumentError, "Not a numeric string `#{data_str}`"
  end
  super(data_str)
end

Class Method Details

.valid_data?(data) ⇒ Boolean

Returns:

  • (Boolean)


109
110
111
# File 'lib/qrcode/encoder/segment.rb', line 109

def self.valid_data?(data)
  data.to_s.match?(/\A\d+\z/)
end

Instance Method Details

#content_sizeObject



117
118
119
120
121
122
123
124
125
126
127
# File 'lib/qrcode/encoder/segment.rb', line 117

def content_size
  data_length = @data.length
  case data_length % 3
  when 0
    (data_length / 3) * 10
  when 1
    ((data_length / 3) * 10) + 4
  when 2
    ((data_length / 3) * 10) + 7
  end
end

#modeObject



113
114
115
# File 'lib/qrcode/encoder/segment.rb', line 113

def mode
  :mode_number
end

#write(buffer) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/qrcode/encoder/segment.rb', line 129

def write(buffer)
  buffer.numeric_encoding_start(@data.size)
  
  @data.scan(/\d{1,3}/).each do |group|
    case group.length
    when 3
      buffer.put(group.to_i, 10)
    when 2
      buffer.put(group.to_i, 7)
    when 1
      buffer.put(group.to_i, 4)
    end
  end
end