5
1

More than 3 years have passed since last update.

【Rails】QRコードを表示する

Last updated at Posted at 2021-06-29

RailsアプリでQRコードを表示したい案件があったので、その時に利用したGem: rqrcode について紹介します。

バージョン情報

  • ruby 2.6.2
  • rails 6.0.3.7
  • rqrcode 2.0.0

Gemのインストール

Gemfileにrqrcodeを追加して、bundle installを実行します。

Gemfile
gem "rqrcode", "~> 2.0"
ターミナル
$ bundle

QRコードの生成

Viewに表示したいので、HelperにQRコード生成用の処理を記載します。
SVG、PNG、ANSI形式がありますが、今回はSVG形式で表示します。

helper.rb
def qrcode
  qrcode = RQRCode::QRCode.new("https://github.com/")
  svg = qrcode.as_svg(
    color: "000",
    shape_rendering: "crispEdges",
    module_size: 6,
    standalone: true,
    use_path: true
  ).html_safe
end
html.erb
<%= qrcode %>

画面にQRコードが表示されました!

QRコード.png

SVGのオプション

各オプションが何なのか気になったので調べました。

offset

QRコード周りのパディングをpx単位で指定出来ます。デフォルトは0です。

fill

QRコードの背景色を指定出来ます。デフォルトはなしです。
例) 青を指定

qrcode = RQRCode::QRCode.new("https://github.com/")
qrcode.as_svg(
  fill: "0000FF",
  color: "000",
  shape_rendering: "crispEdges",
  module_size: 6,
  standalone: true,
  use_path: true
).html_safe

QRコード.png

color

QRコードの色を指定出来ます。 デフォルトは000です。
例) 緑を指定

qrcode = RQRCode::QRCode.new("https://github.com/")
qrcode.as_svg(
  color: "008000",
  shape_rendering: "crispEdges",
  module_size: 6,
  standalone: true,
  use_path: true
).html_safe

QRコード.png

module_size

QRコードのサイズをpx単位で指定出来ます。 デフォルトは11です。

shape_rendering

SVGのshape-rendering属性を指定出来ます。 デフォルトはcrispEdgesです。
shape-rendering属性は、SVGをレンダリングするときにどのようなトレードオフを行うかを指定する属性のようです。
下記4種類から選択します。

  • auto: バランスよくレンダリングを行います
  • crispEdges: アートワークのエッジのコントラストを重視します
  • optimizeSpeed: レンダリング速度を重視します
  • geometricPrecision: 幾何学的な精度を重視します

左から auto, crispEdges, optimizeSpeed, geometricPrecision です。
(QRコードだと違いがあまり分からない...)
QRコード.png

standalone

完全なSVGファイルとして扱う(true)か、他のsvgファイルに埋め込むためのSVGとして扱う(false)かを選択します。
デフォルトはtrueです。

use_path

SVGのレンダリングにパスで描画する(true)か四角形で描画する(false)かを選択します。
デフォルトはfalseです。(将来のバージョンではデフォルトはtrueになる予定)
パスの方がサイズを大幅に削減でき、品質が向上するらしい?

viewbox

svg.widthsvg.heightsvg.viewBoxに置き換えるか選択します。
デフォルトはfalseです。

svg_attributes

カスタムでSVGの属性を設定できます。デフォルトは{}です。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1