RQRCode

repository·main·Indexed 24 days ago

https://github.com/whomwah/rqrcode

A Ruby library for generating and rendering QR codes in multiple formats, including SVG, PNG, ANSI, and HTML. It provides a high-level interface for QR code generation with control over rendering styles, error correction levels, and sizing algorithms. Requires Ruby >= 3.2.0.

Tokens
3.8K
Snippets
8
Records
18
Agent score
83%

What's inside RQRCode

  1. Understand RQRCode benchmark types

    main

    RQRCode benchmarks operate in two distinct modes to provide different insights into performance:

    1. End-to-end (PRIMARY METRIC)

    Measures the complete user workflow: RQRCode::QRCode.new(data).as_svg (or other export methods).

    • Purpose: Reflects real-world performance and the total time a user experiences.
    • Includes: Both QR code generation (rqrcode_core) and the export/rendering process.
    • File naming: ips_e2e_*_YYYYMMDD_HHMMSS.json

    2. Rendering-only (DIAGNOSTIC METRIC)

    Measures only the export performance using pre-generated QR codes.

    • Purpose: Isolates the export format performance to identify specific rendering bottlenecks.
    • Includes: Only the export/rendering process.
    • File naming: ips_*_YYYYMMDD_HHMMSS.json (no e2e in name).

    Key Insight: End-to-end benchmarks often show that QR generation is the primary bottleneck, causing all formats to perform similarly. Rendering-only benchmarks reveal the actual efficiency differences between export formats (e.g., SVG vs. HTML).

  2. Install RQRCode

    main

    To use RQRCode in your Ruby application, add it to your Gemfile:

    gem "rqrcode", "~> 3.0"

    Alternatively, you can install it manually via the command line:

    gem install rqrcode

    Requirements:

    • Minimum Ruby version: >= 3.2.0
    gem "rqrcode", "~> 3.0"
  3. Run RQRCode benchmarks

    main

    To run the performance benchmarks for RQRCode, first install the necessary dependencies using Bundler, then use rake to run specific format benchmarks or the entire suite.

    Install dependencies

    bundle install

    Run specific format benchmarks

    rake benchmark:svg
    rake benchmark:png
    rake benchmark:html
    rake benchmark:ansi
    rake benchmark:format_comparison

    Run all benchmarks

    This runs the full suite (both end-to-end and rendering-only modes) and takes approximately 1-2 minutes.

    rake benchmark:all
    # Install dependencies
    bundle install
    
    # Run specific format benchmarks
    rake benchmark:svg
    rake benchmark:png
    rake benchmark:html
    rake benchmark:ansi
    rake benchmark:format_comparison
    
    # Run all benchmarks (takes ~1-2 minutes)
    rake benchmark:all
  4. Basic usage of RQRCode::QRCode

    main

    You can create a QR code by initializing RQRCode::QRCode.new with the data you want to encode. The simplest way to output a text-based representation is using .to_s, which defaults to using x for dark modules and a space for light modules.

    require "rqrcode"
    
    qr = RQRCode::QRCode.new("https://kyan.com")
    puts qr.to_s
  5. Render QR codes as SVG

    main

    The as_svg method produces a standalone SVG as a String.

    Options:

    • offset: Padding around the QR Code in pixels (default 0).
    • offset_x: X Padding (defaults to offset).
    • offset_y: Y Padding (defaults to offset).
    • fill: Background color (e.g., "ffffff", :white, or :currentColor; default none).
    • color: Foreground color (e.g., "000", :black, or :currentColor; default "000").
    • module_size: Pixel size of each module (default 11).
    • shape_rendering: SVG Attribute: auto | optimizeSpeed | crispEdges | geometricPrecision (default crispEdges).
    • standalone: Whether to make a full SVG file or just an embeddable snippet (default true).
    • use_path: Use <path> instead of <rect> to reduce file size (default false).
    • viewbox: Replace svg.width/height with svg.viewBox for CSS scaling (default false).
    • svg_attributes: A hash of custom <svg> attributes (default {}).
    require "rqrcode"
    
    qrcode = RQRCode::QRCode.new("http://github.com/")
    
    svg = qrcode.as_svg(
      color: "000",
      shape_rendering: "crispEdges",
      module_size: 11,
      standalone: true,
      use_path: true
    )
  6. Render QR codes as ANSI

    main

    The as_ansi method produces a string containing ANSI color codes, suitable for terminal output.

    Options:

    • light: Foreground ANSI code (default "\033[47m").
    • dark: Background ANSI code (default "\033[40m").
    • fill_character: The character used to draw the modules (default ' ').
    • quiet_zone_size: Padding around the edge (default 4).
    require "rqrcode"
    
    qrcode = RQRCode::QRCode.new("http://github.com/")
    
    ansi = qrcode.as_ansi(
      light: "\033[47m", dark: "\033[40m",
      fill_character: "  ",
      quiet_zone_size: 4
    )
  7. Configure QR code generation options

    main

    When initializing a QR code, you can pass several advanced options to control the data structure. These options are passed to the underlying rqrcode_core engine.

    Options:

    • data: The string, QRSegment, or array of Hashes (with data: and mode: keys) to encode.
    • size: (Integer) The size of the QR Code (defaults to smallest needed).
    • max_size: (Integer) The maximum size (defaults to RQRCodeCore::QRUtil.max_size).
    • level: Error correction level. Options: :l (7%), :m (15%), :q (25%), :h (30%, default).
    • mode: The mode of the QR Code (only used when data is a string). Options: :number, :alphanumeric, :byte_8bit (default depends on input).
    # Simple QR code with specific size and error correction
    simple_qrcode = RQRCodeCore::QRCode.new("https://kyan.com", size: 2, level: :m, mode: :byte_8bit)
    
    # Multi-segment encoding using an array of hashes
    multi_qrcode = RQRCodeCore::QRCode.new([
      { data: 'foo', mode: :byte_8bit },
      { data: 'BAR1', mode: :alphanumeric }
    ])
  8. Render QR codes as PNG

    main

    The as_png method returns a ChunkyPNG::Image instance. It supports two sizing algorithms:

    1. Google Sizing (Default): Resizes modules to fit a specific total pixel size. Use the size option.
    2. Original Sizing: Creates an image where 1px = 1 module, then resizes. Use module_px_size or border.

    Options:

    • fill: Background <ChunkyPNG::Color> (default 'white').
    • color: Foreground <ChunkyPNG::Color> (default 'black').

    When using the :file option (ChunkyPNG constraints):

    • color_mode: Use ChunkyPNG::COLOR_* constants (default ChunkyPNG::COLOR_GRAYSCALE).
    • bit_depth: Bit depth for indexed images (default 1).
    • interlace: Boolean for interlacing.
    • compression: Zlib compression level (0-9 or Zlib constant).

    Google Sizing Options:

    • size: Total size of PNG in pixels (default 120).
    • border_modules: Width of white border around modules (default 4). Note: Be careful with quiet zone requirements.

    Original Sizing Options:

    • module_px_size: Image size in pixels.
    • border: Border thickness in pixels.
    require "rqrcode"
    
    qrcode = RQRCode::QRCode.new("http://github.com/")
    
    png = qrcode.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: 120
    )
    
    IO.binwrite("/tmp/github-qrcode.png", png.to_s)
  9. Available RQRCode benchmark suites

    main

    The following benchmark scripts are available in the benchmark/ directory:

    • Format Comparison (benchmark/format_comparison.rb): Compares all export formats head-to-head using a medium-sized QR code.
    • SVG Export (benchmark/svg_export.rb): Tests SVG path mode across different QR sizes.
    • PNG Export (benchmark/png_export.rb): Tests PNG with default sizing across different QR sizes.
    • HTML Export (benchmark/html_export.rb): Tests HTML table export across different QR sizes.
    • ANSI Export (benchmark/ansi_export.rb): Tests ANSI terminal output across different QR sizes.

    Each suite tests three representative QR code sizes:

    • small: ~40 characters (e.g., GitHub URL).
    • medium: ~100 characters (e.g., Lorem ipsum sentence).
    • large: 500 characters (stress test).
  10. Interpret RQRCode benchmark JSON results

    main

    Benchmark results are saved to benchmark/results/ as timestamped JSON files. The files contain performance data (iterations per second) and memory allocation data.

    Common JSON fields

    • iterations_per_second: The number of iterations completed per second. Higher is better.
    • standard_deviation: The percent variation in results. Lower is more consistent.
    • comparison: A multiplier relative to the fastest format. 1.0x is the fastest; higher values indicate slower performance.
    • samples: The number of iterations run for the measurement.

    Example End-to-end Result (ips_e2e_*)

    {
      "label": "All Export Formats (end-to-end)",
      "timestamp": "2025-12-17T21:46:51+00:00",
      "ruby_version": "3.3.4",
      "results": {
        "svg": {
          "iterations_per_second": 16.71,
          "standard_deviation": 0.00,
          "samples": 84,
          "comparison": 1.09
        },
        "ansi": {
          "iterations_per_second": 18.13,
          "standard_deviation": 5.50,
          "samples": 91,
          "comparison": 1.0
        }
      }
    }
    {
      "label": "All Export Formats (end-to-end)",
      "timestamp": "2025-12-17T21:46:51+00:00",
      "ruby_version": "3.3.4",
      "results": {
        "svg": {
          "iterations_per_second": 16.71,
          "standard_deviation": 0.00,
          "samples": 84,
          "comparison": 1.09
        },
        "ansi": {
          "iterations_per_second": 18.13,
          "standard_deviation": 5.50,
          "samples": 91,
          "comparison": 1.0
        }
      }
    }
  11. Render a QR code as ANSI terminal output with `as_ansi`

    main

    The as_ansi method returns a string representing the QR code using ANSI escape codes to set background colors for terminal display. This is useful for printing QR codes directly in a command-line interface.

    Options

    OptionDefaultDescription
    :light"\033[47m"The ANSI code for the light (foreground/quiet) color.
    :dark"\033[40m"The ANSI code for the dark (background/module) color.
    :fill_character" "The character(s) used to fill the modules and quiet zone.
    :quiet_zone_size4The number of rows/columns of the quiet zone to include.
  12. Initialize a QRCode instance

    main

    To create a new QR code, instantiate the RQRCode::QRCode class by passing the data string you wish to encode. You can also pass additional arguments to the constructor which are forwarded to the underlying core engine.

    qr = RQRCode::QRCode.new("your data here")