DEV Community

Cover image for Building a QR code generator with Ruby on Rails
Marco Colli
Marco Colli

Posted on

Building a QR code generator with Ruby on Rails

Today many applications use QR codes.

QR codes are used for many different purposes, like tickets, restaurant menus, payments, sharing a contact or a URL, etc.

A QR code may seem magical to non-tech users, but it is actually very simple. QR codes are simply a different way to write text: instead of using the normal alphabet, that is easily read by humans, we use different signs that are easily read by a machine.

Since you can write any text inside a QR code, you can also write a URL for example. URLs are one of the most common contents of QR codes. A mobile device that scans a QR code, reads the text, and finds a URL, may decide to open that link.

For example, if you have a restaurant menu online you can simply take the URL of the menu and convert it into a QR code: in this way users that scan the QR code will open the restaurant menu. That is exactly how a QR code menu works. And indeed this post is based on the work that I have done for BuonMenu, a QR code menu for restaurants built with Ruby on Rails.

The code

We want to build a simple page with Ruby on Rails that given an arbitrary text or a URL as an input, generates the QR code and allows the user to download it.

First of all create a new Rails application (or open an existing one).

Then add this gem:

# Gemfile

gem 'rqrcode'
Enter fullscreen mode Exit fullscreen mode

And run bundle install.

Then create these routes:

# config/routes.rb

controller :pages do
  get :qr_code_generator
  get :qr_code_download
end
Enter fullscreen mode Exit fullscreen mode

Then the controller:

# app/controllers/pages_controller.rb

class PagesController < ApplicationController
  def qr_code_generator; end

  def qr_code_download
    send_data RQRCode::QRCode.new(params[:content].to_s).as_png(size: 300), type: 'image/png', disposition: 'attachment'
  end
end
Enter fullscreen mode Exit fullscreen mode

This is the code of the view:

<%# app/views/pages/qr_code_generator.html.erb %>

<h1>QR code generator</h1>

<%= form_tag :qr_code_download, method: :get do |f| %>
  <div class="field">
    <%= label_tag 'Text or URL' %>
    <%= text_field_tag :content, nil, required: true %>
  </div>

  <div class="actions">
    <%= submit_tag 'Generate QR code' %>
  </div>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Basically the view is to display a form where the user can add his text or URL and then it sends a request to qr_code_download which actually generates a PNG for the QR code. The QR code will be downloaded on the user device since we use disposition: 'attachment'.

Finally, if we prefer to display the QR code instead of downloading it, we can use a method similar to qr_code_download but with disposition: 'inline'.

Top comments (0)