Creating QR Codes In Rails

Nov 14, 2014, updated Nov 14, 2014

Barby is a great gem for when you have to generate 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.

The first step is to add Barby to your gem file.

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.

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.

# In your view (haml)
%img{src: generate_qr("http://www.leighhalliday.com"), class: "qr-code"}

And voila, a beautiful QR code.

QR Code