Create QR Codes in Ruby on Rails Application

Create QR Codes in Ruby on Rails Application

Barby is a great gem for generating a barcode or QR code. You can choose to output it as any number of barcode types or as a QR code. This example will use a QR code but I have successfully used the Code128 barcode which is fairly common in the retail space.

Add Barby to your gem file:

Gemfile
1
2
gem 'barby',  '~> 0.6.2'
gem 'rqrcode','~> 0.4.2'

Here is an example helper for generating the QR code as base64 encoded png data:

1
2
3
4
5
6
7
8
9
10
def generate_qr(text)
  require 'barby'
  require 'barby/barcode'
  require 'barby/barcode/qr_code'
  require 'barby/outputter/png_outputter'

  barcode = Barby::QrCode.new(text, level: :q, size: 5)
  base64_output = Base64.encode64(barcode.to_png({ xdim: 5 }))
  "data:image/png;base64,#{base64_output}"
end

And an example call from your view:

1
%img{src: generate_qr("http://geekhmer.github.io/"), class: "qr-code"}

So far so good, That’s it!!! See ya!!! :)