安裝
使用 Bundler 或 gem install 安裝 rqrcode gem。
Gemfile
gem 'rqrcode'gem
gem install rqrcode使用 rqrcode 產生 QR碼
在 Ruby 中使用 rqrcode gem 的程式碼範例。
QR Code as SVG
require 'rqrcode'
qr = RQRCode::QRCode.new('https://qrcode.fun')
svg = qr.as_svg(
offset: 0,
color: '1A2B3C',
shape_rendering: 'crispEdges',
module_size: 6,
standalone: true
)
File.write('qrcode.svg', svg)QR Code as PNG
require 'rqrcode'
qr = RQRCode::QRCode.new('https://qrcode.fun')
png = qr.as_png(
bit_depth: 1,
border_modules: 4,
color_mode: ChunkyPNG::COLOR_GRAYSCALE,
color: 'black',
file: nil,
fill: 'white',
module_px_size: 6,
resize_exactly_to: false,
resize_gte_to: false,
size: 300
)
IO.binwrite('qrcode.png', png.to_s)Rails Controller
class QrCodesController < ApplicationController
def show
qr = RQRCode::QRCode.new(params[:data] || 'https://qrcode.fun')
svg = qr.as_svg(module_size: 6, standalone: true)
render inline: svg, content_type: 'image/svg+xml'
end
endQRCode.fun API
透過 API 在 Ruby 中產生 QR碼
使用 Net::HTTP 或 Faraday 從 Ruby 呼叫 QRCode.fun API 產生樣式化 QR碼。
Ruby API 整合
require 'net/http'
require 'json'
uri = URI('https://qrcode.fun/api/generate-qr-styled')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = {
data: 'https://qrcode.fun',
width: 300,
height: 300,
type: 'png',
margin: 10,
dotsOptions: { color: '#1A2B3C', type: 'rounded' },
cornersSquareOptions: { color: '#8564C3', type: 'extra-rounded' },
backgroundOptions: { color: '#FFFFFF' }
}.to_json
response = http.request(request)
result = JSON.parse(response.body)
puts result['data'][0..49]即時 QR碼預覽
立即嘗試使用 Ruby 產生 QR碼。
QR碼預覽
原生函式庫 vs API
比較使用 rqrcode 與 QRCode.fun API。
| 功能 | rqrcode Gem | QRCode.fun API |
|---|---|---|
| 設定複雜度 | gem install + ChunkyPNG 用於影像 | 單次 HTTP 請求 |
| 自訂 | 顏色、模組大小(SVG/PNG) | 完整樣式:顏色、形狀、標誌 |
| 離線支援 | 是 | 需要網路 |
| 維護 | bundle update | 始終保持最新 |
| 輸出格式 | SVG, PNG, ANSI 終端機 | PNG, SVG |
Ruby QR碼使用情境
Ruby 應用中 QR碼的常見情境。
Rails 應用
在 Rails 控制器中產生 QR碼,用於使用者資料、活動票券和雙重認證設定。
背景工作
使用 Sidekiq 或 Active Job 非同步建立 QR碼,用於批量標籤產生和郵件行銷活動。
API 端點
建構回傳 QR碼影像或 SVG 的 API 端點,供行動應用和第三方整合使用。
自動化腳本
撰寫 Ruby 腳本批量產生 QR碼,用於庫存、資產標記和活動管理。
常見問題
關於使用 Ruby 產生 QR碼的常見問題。
rqrcode 是最受歡迎且維護良好的 Ruby QR碼 gem。它支援 SVG 和 PNG 輸出,並與 Rails 良好整合。