安装
使用 Bundler 或 gem install 安装 rqrcode gem。
Gemfile
gem 'rqrcode'gem
gem install rqrcode使用 rqrcode 生成二维码
在 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 中生成二维码
使用 Net::HTTP 或 Faraday 从 Ruby 调用 QRCode.fun API 生成样式化二维码。
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]实时二维码预览
立即尝试使用 Ruby 生成二维码。
二维码预览
原生库 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 二维码使用场景
Ruby 应用中二维码的常见场景。
Rails 应用
在 Rails 控制器中生成二维码,用于用户资料、活动票据和双因素认证设置。
后台任务
使用 Sidekiq 或 Active Job 异步创建二维码,用于批量标签生成和邮件营销活动。
API 端点
构建返回二维码图像或 SVG 的 API 端点,供移动应用和第三方集成使用。
自动化脚本
编写 Ruby 脚本批量生成二维码,用于库存、资产标记和活动管理。
常见问题
关于使用 Ruby 生成二维码的常见问题。
rqrcode 是最流行且维护良好的 Ruby 二维码 gem。它支持 SVG 和 PNG 输出,并与 Rails 良好集成。