Generate QR Code with gem rqrcode in Ruby on Rails

Tram Ho

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:

The command RQRCode :: (” “) 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:

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


Share the news now

Source : Viblo