1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[macOS][Ruby] 任意の文字列から QR コードを生成し、ターミナルに表示する

Last updated at Posted at 2025-06-19

やりたいこと

任意の文字列から QR コードを生成し、ターミナルに表示したいです。

前提

  • OS は macOS
  • ターミナル が kitty の terminal graphics protocol に適合していること
    • Ghostty, Konsole, st, Warp, wayst, WezTerm
    • 僕は Warp を使っています

方法

必要なライブラリをインストールします。ターミナル上に画像を表示するために kitty というターミナルエミュレータを、QR コードを生成するために RQRCode という Gem をインストールします。

$ brew install kitty
$ gem install rqrcode

以下の Ruby スクリプトを用意します。

show_qr_code.rb
require 'rqrcode'
require 'tmpdir'

qrcode = RQRCode::QRCode.new(ARGV[0])

# 生成した QR コードを一時的に PNG ファイルとして保存し、スクリプト実行後に破棄する。
Dir.mktmpdir do |dir|
  tmp_path = File.join(dir, 'qrcode.png')
  File.write(tmp_path, qrcode.as_png)

  system('kitty', '+kitten', 'icat', tmp_path)
end

任意の文字列をコマンドライン引数として与えて Ruby スクリプトを実行すると、ターミナル上に QR コードが表示されます。

run show_qr_code.rb

試しに iPhone の QR コードリーダーでスキャンすると、無事にコマンドライン引数として与えた URL にアクセスできました!

screenshot

バージョン情報

$ ruby -v
ruby 3.4.3 (2025-04-14 revision d0b7e5b6a0) +PRISM [arm64-darwin24]

$ gem list | grep rqrcode
rqrcode (3.1.0)
rqrcode_core (2.0.0)

$ kitty --version
kitty 0.42.1 created by Kovid Goyal

おまけ

Kernel.#system に複数の引数を渡すと、シェルを介さずにコマンドを実行することになり、コマンドインジェクション対策になるということを知りました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?