Plugins and extensions

suggest change

Ruby is designed for high extensibility. Applications and libraries can be extended through two primary mechanisms:

  1. Ruby Plugin Architecture: Modular, dynamically discovered plugins using self-registering classes and gem-based discovery (Gem.find_files).
  2. Native Extensions: Compiled C or Rust libraries loaded directly into CRuby via the C API for hardware acceleration, low-level OS bindings, or CPU-intensive tasks.

1. Building a Dynamic Ruby Plugin Architecture

A clean plugin system allows third-party developers to contribute plugins without modifying your core application codebase.

Plugin Registration Pattern

module App
  module PluginRegistry
    @plugins = {}

    def self.register(name, plugin_class)
      @plugins[name.to_sym] = plugin_class
      puts "Registered plugin: #{name}"
    end

    def self.get(name)
      @plugins.fetch(name.to_sym) { raise "Unknown plugin: #{name}" }
    end

    def self.all
      @plugins
    end
  end

  # Base class enforcing plugin contract
  class BasePlugin
    # Subclasses register themselves by declaring a name: `plugin_name :slack`.
    # (An `inherited` hook can't do this: it runs before the subclass body,
    # so methods the subclass defines don't exist yet.)
    def self.plugin_name(name = nil)
      return @plugin_name if name.nil?
      @plugin_name = name
      PluginRegistry.register(name, self)
    end

    def execute(payload)
      raise NotImplementedError, "#{self.class} must implement #execute"
    end
  end
end

Third parties define plugins simply by inheriting from the base class:

class SlackNotifierPlugin < App::BasePlugin
  plugin_name :slack

  def execute(payload)
    puts "Posting alert to Slack: #{payload}"
  end
end

# Executing registered plugins dynamically:
plugin = App::PluginRegistry.get(:slack).new
plugin.execute("Deploy completed successfully!")

2. Auto-Discovering Gem Plugins with Gem.find_files

To allow third parties to publish plugins as standalone RubyGems (e.g. my_app-slack, my_app-datadog), your application can search installed gems on the load path:

module App
  def self.load_plugins!
    # Searches all installed gems for files matching pattern
    Gem.find_files("my_app/plugins/*.rb").each do |plugin_path|
      begin
        require plugin_path
      rescue LoadError => e
        warn "Failed to load plugin at #{plugin_path}: #{e.message}"
      end
    end
  end
end

App.load_plugins!

Any gem placing Ruby files in lib/my_app/plugins/ will be discovered and required automatically.


3. Native C Extensions with mkmf

When pure Ruby performance is insufficient, you can write C extensions that compile into native shared libraries (.so / .bundle / .dll).

Step 1: Create extconf.rb

The extconf.rb file uses the standard library mkmf (Make Makefile) to detect system headers and generate a platform-specific Makefile:

# ext/fast_math/extconf.rb
require 'mkmf'

# Name of the extension module to compile
extension_name = 'fast_math'

dir_config(extension_name)
create_makefile("fast_math/#{extension_name}")

Step 2: Write the C Source (fast_math.c)

Every native extension must export an initialization function named Init_<extension_name>:

// ext/fast_math/fast_math.c
#include "ruby.h"

// C implementation of fast integer factorial
static VALUE rb_fast_factorial(VALUE self, VALUE rb_num) {
    long n = NUM2LONG(rb_num);
    if (n < 0) {
        rb_raise(rb_eArgError, "Factorial not defined for negative numbers");
    }

    long long result = 1;
    for (long i = 2; i <= n; i++) {
        result *= i;
    }

    return LL2NUM(result);
}

// Entry point called by Ruby VM when required
void Init_fast_math(void) {
    VALUE mFastMath = rb_define_module("FastMath");
    rb_define_singleton_method(mFastMath, "factorial", rb_fast_factorial, 1);
}

Step 3: Compiling and Testing

cd ext/fast_math
ruby extconf.rb
make

In Ruby:

require './ext/fast_math/fast_math'

puts FastMath.factorial(12) #=> 479001600

Step 4: Declaring in .gemspec

To compile native C extensions automatically when users install your gem:

Gem::Specification.new do |spec|
  spec.name = "fast_math"
  spec.extensions = ["ext/fast_math/extconf.rb"]
  # ...
end

4. Modern Native Extensions in Rust (magnus)

Modern Ruby libraries increasingly use Rust instead of C for native extensions, eliminating buffer overflows, memory leaks, and segmentation faults while matching C's raw speed.

Using the popular magnus crate:

// src/lib.rs
use magnus::{function, prelude::*, Error, Ruby};

fn fast_fibonacci(n: usize) -> u64 {
    let mut a = 0;
    let mut b = 1;
    for _ in 0..n {
        let temp = a;
        a = b;
        b += temp;
    }
    a
}

#[magnus::init]
fn init(ruby: &Ruby) -> Result<(), Error> {
    let module = ruby.define_module("FastRust")?;
    module.define_singleton_method("fibonacci", function!(fast_fibonacci, 1))?;
    Ok(())
}

Paired with the rb-sys build toolchain, Rust extensions compile into native shared libraries callable directly from Ruby:

require 'fast_rust'

puts FastRust.fibonacci(40) #=> 102334155

Best Practices

  1. Provide a Pure Ruby Fallback: When shipping gems with native extensions, provide a fallback pure-Ruby implementation so users on exotic architectures or JRuby/TruffleRuby can still run your gem.
  2. Handle Exceptions Gracefully in Native Code: In C extensions, unhandled signals or illegal pointer dereferences crash the entire Ruby process. Use rb_protect() or write in Rust to safeguard against segmentation faults.
  3. Use Namespace Prefixes for Plugins: Always namespace plugin files (e.g. my_app/plugins/) to avoid polluting the global Ruby $LOAD_PATH.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents