-
Notifications
You must be signed in to change notification settings - Fork 81
Generate QR code with rqrcode gem
Zain Butt edited this page Jan 6, 2020
·
5 revisions
This example shows how to create a QR code only with html and css, this help if you don't like to use external library, like minimagic.
Gemfile
gem 'active_model_otp'
gem 'rqrcode'
then run bundle install
First create the rails migration with the One Time Password secret key
$ rails g migration AddOtpSecretKeyToUsers otp_secret_key:string
=>
invoke active_record
create db/migrate/20130707010931_add_otp_secret_key_to_users.rb
Now, we have to say our user model use the gem app/models/user.rb
, now after create a object the secret key
is auto-generated.
class User < ActiveRecord::Base
has_one_time_password
end
now in show action of users controllers we will show the qr code app/controllers/users.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@qr = RQRCode::QRCode.new(@user.provisioning_uri("Your app name"), :size => 7, :level => :h )
end
end
In the show view, we have to render the qr code in a html table app/views/users/show.html.erb
## This is your QR code
<table class="qr">
<% @qr.modules.each_index do |x| %>
<tr>
<% @qr.modules.each_index do |y| %>
<% if @qr.qrcode.checked?(x,y) %>
<td class="black"/>
<% else %>
<td class="white"/>
<% end %>
<% end %>
</tr>
<% end %>
</table>
And, yes, add some style to the table
app/assets/stylesheets/users.css.scss
.qr {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
width: 50%;
}
.qr td {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
padding: 0;
margin: 0;
width: 10px;
height: 10px;
}
.qr td.black { background-color: #000; }
.qr td.white { background-color: #fff; }