Rails: QR code generating with rqrcode
1 min readJan 18, 2021
Creating and rendering QR codes in rails app is easy now. rqrcode
gem provides this functionality. Follow this tutorial. At the end, you will be having a QR code rendered on your app. Scanning that code will ask you to open Google
in browser. You may replace the URL as you need.
Installing
Add this line to your application’s Gemfile
:
gem 'rqrcode'
or install manually:
gem install rqrcode
Basic usage example
You can use this helper: /helpers/qrcode_helper.rb
module QrcodeHelper
require 'rqrcode'
def render_qr_code text, size = 3
return if text.to_s.empty?
qr = RQRCode::QRCode.new(text)
sizeStyle = "width: #{size}px; height: #{size}px;"
content_tag :table, class: "qrcode pull-right" do
qr.modules.each_index do |x|
concat(content_tag(:tr) do
qr.modules.each_index do |y|
color = qr.qrcode.checked?(x, y) ? 'black' : 'white'
concat content_tag(:td, nil, class: color, style: sizeStyle)
end
end)
end
end
end
end
Into your view some_view.html.erb
<%= render_qr_code("https://www.google.com/") %>
And you need to add style for your code qrcode.css.scss
table.qrcode {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
margin-top: 100px;
margin-bottom: 12px;
td {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
padding: 0;
margin: 0;
width: 3px;
height: 3px;
&.black {
background-color: #000 !important
}
&.white {
background-color: #fff !important
}
}
}
Reload the webpage and scan the QR code. We’re done..!