In this article, I will guide you to create a very simple QR Code with the gem rqrcode
1, Install gem
Like any other gem installation in addition to Gemfile
:
gem 'rqrcode'
or install by command
gem install rqrcode
Next add the config/application.rb
file:
require ‘rqrcode’
2, Create QR Code
I will create a QR Code which is a link to the github page
For example:
1 2 3 4 5 6 7 8 9 10 11 12 | def index qrcode = RQRCode::QRCode.new("http://github.com/") @svg = qrcode.as_svg( offset: 0, color: '000', shape_rendering: 'crispEdges', module_size: 6, standalone: true ) end |
The command RQRCode :: QRCode.new (” http://github.com/ “) will generate a QR Code with the content of the link to the github page. I will try to display this QRCode code
It doesn’t look like QR Code but a string @@, I try inspect element
It looks quite similar to a QR Code if you replace the ‘x’ with a small black square
With as_svg function will help convert the other QR Code into svg format and can be used, the as_svg function comes with some options such as:
- offset: the width of the outer envelope for the QR Code
- color: color for QR Code
- module_size: the size of each colored square in the QR Code
I will show test <%= @svg %>
This is because the as_svg function will generate SVG, but in string format, to display svg images just use <%= @svg.html_safe %>
Now we have a complete QR Code
In addition to creating QR Code in SVG format, gem rqrcode can also generate QR Code in PNG format
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def index qrcode = RQRCode::QRCode.new("http://github.com/") @png = qrcode.as_png( bit_depth: 1, border_modules: 4, color_mode: ChunkyPNG::COLOR_GRAYSCALE, color: 'black', file: nil, fill: 'white', module_px_size: 6, resize_exactly_to: false, resize_gte_to: false, size: 300 ) end |
The as_png function will create 1 ChunkyPNG :: Image and to use it, in the view, just the following: <img src="<%= @png.to_data_url %>" />
And the result also gives a QR Code which is the same as using as_svg but with PNG format