Introduction
Have you ever thought of organizing a small 4.0 event? If you answered yes to this question, then you are most likely interested in making money and selling tickets. One way to verify that someone has purchased a ticket is via QR Code. Now I will guide you to build a Ruby on Rails web that can generate QR code using gem rqrcode
RQRCode is a library for creating and displaying QR codes in many different formats. It has a simple interface with all standard QR code options. It is adapted from the Javascript library by Kazuhiko Arase.
Installation
By default you already know how to install ruby and rails.
Add the gem 'rqrcode'
to your Gemfile in your app. Or you can install it manually using the command line gem install rqrcode
.
Create a model called Ticket
with attribute code
and action show
.
Setup route for Ticket: resources :tickets, only: :show
Basic usage example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | require 'rqrcode' qr = RQRCode::QRCode.new('http://github.com') result = '' qr.qrcode.modules.each do |row| row.each do |col| result << (col ? 'X' : 'O') end result << "n" end puts result |
Advanced Options
These are the different QR Code generation options provided by rqrqcode_core.
string – the string you wish to encode
size – the size of the qrcode (default 4)
level – the error correction level, can be:
- Level: l 7% of code can be restored
- Level: m 15% of code can be restored
- Level: q 25% of code can be restored
- Level: h 30% of code can be restored (default: h)
mode – the mode of the qrcode (defaults to alphanumeric or byte_8bit, depending on the input data):
- : number
- : alphanumeric
- : byte_8bit
- : kanji Example: qrcode = RQRCodeCore :: QRCode.new (‘VUONG’, size: 1, level:: m, mode:: alphanumeric)
Render types
Create sample data with seed:
1 2 3 4 | 10.times do Ticket.create! code: SecureRandom.hex end |
as SVG
Basic
1 2 3 4 5 6 7 8 9 10 11 12 13 | require 'rqrcode' qrcode = RQRCode::QRCode.new("26946d181d1d45717d186d492843dedc") # NOTE: showing with default options specified explicitly svg = qrcode.as_svg( offset: 0, color: '000', shape_rendering: 'crispEdges', module_size: 6, standalone: true ) |
Rails
1 2 3 | def show @ticket = Ticket.find_by params |