OCRAN — turn Ruby scripts into standalone executables (.exe) for Windows, Linux and macOS


OCRAN (One-Click Ruby Application Next) is a Ruby-to-executable packager:
ocran app.rb turns a Ruby script into a single .exe (Windows) or native
binary (Linux, macOS) that runs on machines without Ruby installed. It is
the maintained successor of OCRA for
Ruby 3.3 and newer.
OCRAN packages Ruby applications for
distribution. It bundles your script, the Ruby interpreter, gems, and native
libraries into a single self-contained artifact that runs without requiring
Ruby to be installed on the target machine.
Quick start:
gem install ocran
ocran app.rb # → app.exe on Windows, ./app on Linux/macOS
See the FAQ and the comparison with other Ruby packagers.
OCRAN supports four output formats, all cross-platform:
- Self-extracting executable — bundles everything into a single binary that unpacks and runs transparently, with no Ruby installation required. Produces a
.exe on Windows, and a native executable on Linux and macOS.
- macOS app bundle (
--macosx-bundle) — wraps the executable in a .app bundle for Finder integration, Dock icons, and code signing.
- Directory (
--output-dir) — copies all files into a folder with a ready-to-run launch script (.sh on Linux/macOS, .bat on Windows).
- Zip archive (
--output-zip) — same as directory output, packed into a .zip.
OCRAN is a fork of OCRA maintained for
Ruby 3.3+ compatibility.
If you run into errors while using OCRAN, please check the OCRAN issues first.
Recommended usage
The most common use-case is shipping a program to users running Windows / Linux / macOS
who do not have Ruby installed. By default, each time the .exe / executable is opened it
extracts the Ruby interpreter and your code to a temporary directory and runs
them from there.
Because extraction takes time on each launch, use --output-dir or
--output-zip to produce a portable directory/archive that runs with the
bundled Ruby on Linux, macOS, or Windows.
If using Windows you can use the Inno Setup
option (--innosetup) to produce a proper installer that extracts once to a
permanent directory.
If you want one binary that runs on all three systems and starts
without extracting anything, package a cosmopolitan Ruby with
--cosmo-ruby <ruby.com> (experimental, see
Experimental options). Grab the interpreter from
CosmoRuby releases
and point OCRAN at it:
ocran app.rb --cosmo-ruby ./ruby.com
It needs no compiler and no installer, and the same file runs on Linux,
macOS and Windows, on x86-64 and ARM.
You can easily generate binaries for the supported Operating Systems with GitHub
Actions — see Building for multiple platforms with GitHub Actions.
Features
- Windows/Linux/macOS executable — self-extracting, self-running executable (primary output)
- macOS app bundle —
.app bundle with Info.plist for Finder/Dock/code-signing (--macosx-bundle)
- Directory output — portable directory with a launch script (
--output-dir)
- Zip archive output — portable zip with a launch script (
--output-zip)
- LZMA compression (optional, default on, for
.exe only)
- Both windowed and console mode supported (Windows)
- Gems included based on actual usage, or from a Bundler Gemfile
- Code-signing compatible
- Multibyte (UTF-8) path support on Windows 10 1903+
Problems & Bug Reporting
If you experience problems with OCRAN or have found a bug, please use the
issue tracker on GitHub (http://github.com/largo/ocran/issues).
Safety
As this gem ships with binary blobs, releases are securely built on GitHub
Actions. Feel free to verify that the published gem matches the source.
This repository includes lzma.exe from the
official ip7z/7zip release
(version 22.01, from lzma2201.7z), used to compress Windows executables.
stub.exe, stubw.exe and the Linux/macOS stub are compiled from source in this
repository.
Installation
gem install ocran
Alternatively, download from http://rubygems.org/gems/ocran or
https://github.com/largo/ocran/releases/.
Synopsis
Building an executable:
ocran script.rb
Packages script.rb, the Ruby interpreter, and all dependencies (gems and
DLLs) into script.exe or script on Linux or macOS.
Building a portable directory (Linux / macOS / Windows):
ocran --output-dir myapp/ script.rb
Copies all files into myapp/ and writes a script.sh (or script.bat on
Windows) launch script.
Building a macOS app bundle:
ocran --macosx-bundle script.rb
Produces script.app/ — a standard macOS .app bundle containing the
self-extracting executable at Contents/MacOS/script and an Info.plist.
Open it with open script.app or double-click it in Finder.
ocran --macosx-bundle --output MyApp --bundle-id com.example.myapp --icon icon.icns script.rb
Custom name, bundle identifier and icon (must be .icns format). The icon is
placed at Contents/Resources/AppIcon.icns and referenced in Info.plist.
Building a zip archive:
ocran --output-zip myapp.zip script.rb
Same as --output-dir, but packages the result into a zip file. Requires
zip on Linux/macOS or PowerShell on Windows.
Command line:
ocran [options] script.rb [<other files> ...] [-- <script arguments> ...]
Options:
ocran --help
ocran -h
General options:
--help, -h: Display available command-line options.
--quiet: Suppress all output during the build process.
--verbose: Provide detailed output during the build process.
--version: Display the OCRAN version number and exit.
Packaging options:
--dll <dllname>: Include additional DLLs from the Ruby bin directory.
--add-all-core: Add all standard Ruby core libraries to the executable.
--gemfile <file>: Include all gems and dependencies listed in a Bundler Gemfile.
--no-enc: Exclude encoding support files to reduce output size.
Gem content detection modes:
These options control which files from included gems are added to the output.
--gem-minimal[=gem1,..]: Include only scripts actually loaded during the dependency run.
--gem-guess[=gem1,..]: Include loaded scripts and a best guess of other needed files (DEFAULT).
--gem-all[=gem1,..]: Include all scripts and important files from the gem.
--gem-full[=gem1,..]: Include every file in the gem directory.
--gem-spec[=gem1,..]: Include the files listed in the gemspec.
Fine-tuning flags:
--[no-]gem-scripts[=..]: Include/exclude non-loaded script files (.rb, .rbw).
--[no-]gem-files[=..]: Include/exclude data files.
--[no-]gem-extras[=..]: Include/exclude extras (READMEs, tests, C sources).
Auto-detection options:
--no-dep-run: Skip running the script to detect dependencies. Use this if your script has side effects during load or if you are manually specifying all dependencies. Nothing the script loads is detected then, so you usually need --add-all-core for the standard library and --gemfile with --gem-full (or --gem-all) for gems; OCRAN warns when they are missing.
--no-autoload: Do not attempt to load autoloaded constants.
--no-autodll: Disable automatic detection of runtime DLL dependencies.
Output options:
--output <file>: Name the generated executable. Defaults to ./<scriptname>.exe on Windows and ./<scriptname> on Linux/macOS.
--output-dir <dir>: Output all files to a directory with a launch script instead of building an executable. Works on Linux, macOS, and Windows.
--output-zip <file>: Output a zip archive containing all files and a launch script. Requires zip (Linux/macOS) or PowerShell (Windows).
--macosx-bundle: Build a macOS .app bundle. Use --output to set the bundle name (default: <scriptname>.app). (macOS)
--bundle-id <id>: Set the CFBundleIdentifier in Info.plist (default: com.example.<appname>). Used with --macosx-bundle.
--no-lzma: Disable LZMA compression (faster build, larger executable).
--innosetup <file>: Use an Inno Setup script (.iss) to create a Windows installer.
Executable options:
--windows: Force a Windows GUI application (uses rubyw.exe). (Windows only)
--console: Force a console application (uses ruby.exe). (Windows only)
--chdir-first: Change working directory to the app’s extraction directory before the script starts.
--chdir-exe-dir: Change working directory to the directory containing the executable before the script starts. Use this when your app reads or writes files that live next to the .exe using relative paths. Cannot be combined with --chdir-first.
--icon <ico>: Replace the default icon with a custom .ico file.
--rubyopt <str>: Set RUBYOPT when the executable runs.
--debug: Enable verbose output when the generated executable runs.
--debug-extract: Unpack to a local directory and do not delete after execution (useful for troubleshooting).
Windows resource options:
These set the PE resources of the generated executable, with the same names
as rcedit. They apply to the
self-extracting .exe and to the wrapper .exe of --output-dir,
--output-zip and --innosetup. All are opt-in: without them the
executable is built as before. (Windows only)
--set-version-string <key> <value> (alias --version-string): Add a StringFileInfo entry such as CompanyName, ProductName, FileDescription or LegalCopyright. Repeat for each key.
--set-file-version <x.y.z.w> (alias --file-version): Set the numeric and string file version.
--set-product-version <x.y.z.w> (alias --product-version): Set the numeric and string product version.
--set-resource-string <id> <value> (alias --resource-string): Set an entry of the RT_STRING table by its numeric id.
--set-requested-execution-level <level> (alias --uac-level): Set the UAC level in the manifest: asInvoker (the default), highestAvailable or requireAdministrator.
--application-manifest <file> (alias --manifest): Replace the built-in application manifest with the given file. --set-requested-execution-level still applies to it.
ocran app.rb --set-version-string CompanyName "Example Ltd" \
--set-version-string ProductName "Example App" \
--set-version-string FileDescription "Example App" \
--set-file-version 1.2.0.0 --set-product-version 1.2.0.0
An unsigned executable with no version information, which extracts files
to %TEMP% and runs them, is what antivirus and EDR heuristics expect of a
malware packer. Version information, an icon and a code signature give it
an identity instead. docs/av-edr-false-positives.md
goes through these steps in order of impact.
Experimental options:
-
--static-runtime <runtime-dir>: Build a single executable for Windows,
Linux or macOS that runs the application without extracting anything:
no temporary directory, no DLLs or shared libraries written to disk. The
executable is a statically linked Ruby (the static runtime) with the
application as a plain ZIP archive: appended on Windows and Linux, in a
section of its own on macOS (__OCRAN,__zip), where appended data would
break the code signature. The Linux runtime is linked against musl and
fully static, so it runs on any x86_64 distribution.
ocran app.rb --static-runtime path/to/runtime # app.exe (Windows) or app (Linux, macOS)
unzip -l app.exe # lists exactly what will run (Linux: app)
unzip -p app.exe ocran/manifest.sha256 # SHA-256 of the runtime and every file
segedit app -extract __OCRAN __zip app.zip # macOS: the archive is a section
unzip -l app.zip
The runtime directory holds ocran-runtime(.exe), its own standard
library and bundled gems (lib/ruby/) and runtime.json; build one with
runtime/build-runtime.sh (Windows, MinGW, on Linux), the scripts in
runtime/mswin/ (Windows, Visual Studio Build Tools) or
runtime/linux/build-runtime.sh (Linux x86_64, musl) or
runtime/macos/build-runtime.sh (macOS, on a Mac). The Windows
runtimes import only DLLs that ship with Windows and need no VC++
redistributable; the Linux runtime imports nothing at all; the macOS
runtime links only libraries of macOS itself (libSystem, libiconv,
CoreFoundation). On macOS every executable is linked at packaging time,
with its archive, so packaging for macOS needs a Mac with clang (Xcode or
the Command Line Tools); the linker signs the result ad hoc, and it can
be signed again with codesign. Which system
the executable is for follows from the runtime, not from the build host:
a Linux build host can package for Windows and the other way round, as
long as the application does not depend on platform-specific gems. See
runtime/README.md for how it works and how it is
built. CI builds and tests the three runtimes and publishes each as a
reproducible archive (a zip for Windows, a tarball otherwise) with a
signed build provenance attestation
(gh attestation verify <archive> -R Largo/ocran); releases from 1.5.1
on have them attached.
Dependency detection runs as usual, under the build host’s Ruby, which
must have the runtime’s API version (e.g. 4.0.0). The standard library
and the gems the runtime ships come from the runtime, so that they match
its interpreter; OCRAN says when one replaces a different version on the
build host. C extensions are linked into the executable, since nothing
can be loaded from inside it: those the runtime has (openssl, psych,
zlib, fiddle, win32ole, bigdecimal, …) are used as they are; any other
gem’s extension is built from the gem’s source against the runtime’s
SDK (sdk/ in the runtime directory) and linked into a runtime of the
application’s own. That needs a compiler for the runtime: for a MinGW
runtime x86_64-w64-mingw32ucrt-gcc on Linux, or on Windows
RubyInstaller’s MSYS2 GCC named with OCRAN_RUNTIME_CC=gcc (with
ucrt64\bin and usr\bin on PATH); for an mswin runtime cl and
nmake of Visual Studio Build Tools, from a developer prompt; for a
Linux runtime musl-gcc; for macOS clang. Gems that
need a C library get the one the SDK provides: nokogiri uses its
libxml2/libxslt, tiny_tds its FreeTDS. A precompiled platform gem is
built from its source gem of the same version, which OCRAN fetches from
the configured gem sources into ~/.cache/ocran/gems, together with the
gems its build needs that are not installed (nokogiri’s extconf.rb needs
mini_portile2), installed there for the build only. Failing that, it is
built from the C sources it carries, if any (gem install <gem> --platform ruby installs the source gem).
Licenses: the executable is statically linked - Ruby, OpenSSL and
the other libraries are inside it, and their license texts are packed
into it as ocran/licenses/. Two optional libraries are under the LGPL
(GNU libiconv, FreeTDS: used by nokogiri and tiny_tds), which asks that
users can replace them; --runtime-dll iconv,sybdb ships them as DLLs
next to the executable instead. Read
runtime/LICENSES.md before distributing.
OpenSSL verifies certificates against the Windows certificate store, as
Windows itself does, and on Linux and macOS against the system’s CA
bundle - no CA file is packed or needed. The application reads its own files as
usual (require, require_relative, autoload, File.read,
Dir.glob, __dir__, DATA); their paths lie inside the executable
(C:/app/tool.exe/src/tool.rb) and cannot be written. Files next to the
executable are found through ENV["OCRAN_EXECUTABLE"]. --windows makes
a GUI-subsystem executable; --icon and the version-resource options
work as for the stub, on any build host (OCRAN writes the resources in
Ruby). --dll and the output-directory formats do not apply.
Experimental.
-
--runtime-dll <lib,...>: With --static-runtime, link these C libraries of the
runtime’s SDK as DLLs shipped next to the executable rather than into it
(the SDK has DLL builds of iconv and sybdb, the LGPL libraries).
OCRAN copies them, and the DLLs they need, next to the executable.
-
--cosmo-ruby <ruby.com>: Package a cosmopolitan-built Ruby (an APE)
as the bundled interpreter instead of the host Ruby. The produced
.com contains no host-native code at all and runs on Linux, Windows
and macOS, on x86-64 and ARM:
ocran app.rb --cosmo-ruby /path/to/ruby.com
Where to get ruby.com. Download a release from
CosmoRuby — one
file, no installation:
curl -L -o ruby.com https://github.com/Largo/cosmoruby/releases/latest/download/ruby.com
chmod +x ruby.com
ocran app.rb --cosmo-ruby ./ruby.com
Any self-contained cosmopolitan Ruby works, but CosmoRuby is what this
option is developed and tested against. Releases from v4.0.6-cosmo3
onwards also support the ZIP packaging mode described below, which
needs no C compiler at all; earlier releases fall back to building a
launcher stub, which needs cosmocc. Building your own is documented
in CosmoRuby’s BUILDING.md.
This one option is the whole command line. The payload APE must be
fully self-contained, i.e. carry its standard library in its embedded
ZIP store (/zip/lib/ruby/...) — upstream cosmopolitan Ruby builds
do.
Two ways of producing the executable. OCRAN picks the better one
automatically, from the interpreter you give it:
|
ZIP packaging (default when supported) |
APE launcher stub (fallback) |
| How |
the executable is the interpreter, with your application injected into its ZIP store |
an APE stub carries the interpreter and your application as a payload |
| Compiler |
none |
cosmocc (located automatically) |
| At every start |
nothing is unpacked |
~21 MB unpacked into a temp directory |
| Startup (see below) |
0.23 s Linux / 0.49 s Windows |
0.79 s Linux / 1.5 s Windows |
| Temp directory |
never created |
created per run, leaked if the process is killed |
| Size |
interpreter + application |
LZMA-compressed, roughly half |
__dir__ of your script |
/zip/ocran/src (inside the executable) |
the temp directory |
ZIP packaging is used when the given interpreter runs an embedded
/zip/main.rb on startup (CosmoRuby builds do; OCRAN detects it by
inspecting the binary). Otherwise OCRAN falls back to the launcher
stub and locates a cosmocc toolchain for it (see --cosmo below).
Passing --cosmo <toolchain> explicitly always selects the launcher
stub, as do --output-dir, --output-zip, --innosetup and
--macosx-bundle, which are not single binaries.
What changes for your application under ZIP packaging (nothing
below applies to the launcher stub):
- Your files are not on disk at run time.
$0, __FILE__ and
__dir__ point into the executable’s archive
(/zip/ocran/src/...), on every platform and with / separators.
Reading, require, require_relative and Dir.glob all work
there; writing does not, and the archive cannot be a working
directory (Dir.chdir("/zip") fails).
- Files that ship next to the executable are unaffected: resolve
them through
ENV["OCRAN_EXECUTABLE"], which is the full path of
the running .com exactly as before (issue #32). Do not use
__dir__ for that — it never meant “next to the exe” in either
mode, but here it is obviously wrong instead of subtly wrong.
--chdir-first changes into the directory containing the
executable, since the application directory does not exist on disk;
--chdir-exe-dir does the same.
- The whole command line reaches
ARGV, unchanged. The interpreter
claims none of it, so app.com --version, app.com -v and
app.com -- x behave exactly as they would for a natively compiled
program (-- is an ordinary argument, not a separator). This needs
a cosmopolitan Ruby with the fix from 2026-08; older builds parsed
leading option-shaped arguments themselves and failed with
invalid option --verbose.
RUBYOPT is applied as far as it can be from inside the process:
-I and -r are replayed, other flags are reported at build time
and dropped (the interpreter has already started).
--icon and --debug-extract have no effect and are reported.
- The executable is not compressed (it has to stay runnable), so
--no-lzma makes no difference to its size; individual packed files
are deflated.
- Exit codes are your application’s, exactly, on every platform
including Windows. (Cosmopolitan encodes a POSIX wait status into
the Windows process exit code, so
exit 3 used to arrive as 768;
both the interpreter and the launcher stub now report the plain
status.)
Notes that apply to both:
- The payload is run once on the build host (via
/bin/sh, using the
APE’s shell-script self-bootstrap) to validate it and to query its
version and embedded gem directory.
- Dependency detection still runs under the host Ruby. Standard
library requires resolve at runtime from the payload’s embedded
stdlib (the host stdlib is not packed); a warning is printed when
host and payload Ruby versions differ.
- Pure-Ruby application files and pure-Ruby gems are packed as usual
and activated via
GEM_PATH. Native gems cannot work (the payload
is a statically linked x86_64-cosmo binary that cannot dlopen):
gems that the payload provides itself (e.g. json, psych,
sqlite3) are simply not packed, so the payload’s own copy serves;
any other native gem aborts the build. This covers gems built from
source (spec.extensions) as well as precompiled platform gems
(e.g. sqlite3-2.9.5-x86_64-linux-gnu), which declare no
extensions but ship a prebuilt .so in their lib directory.
--add-all-core and encoding-support packing are no-ops (the
payload embeds its complete stdlib and encodings).
- Linux/macOS build hosts only, console applications only
(
--windows is rejected — cosmocc has no GUI stubw equivalent).
The launcher-stub fallback additionally needs make. The default
output name uses the .com extension (APE convention), e.g.
app.rb → app.com; an explicit --output is used verbatim.
Measured with a 8-file CLI using four pure-Ruby gems (thor,
terminal-table, rainbow, unicode-display_width) and cosmopolitan Ruby
4.0.6, average of 10 runs:
| Build |
Size |
Startup (Linux) |
Startup (Windows 11) |
| ZIP packaging |
21.5 MB |
0.23 s |
0.49 s |
Launcher stub, --no-lzma |
22.8 MB |
0.24 s |
1.09 s |
| Launcher stub, LZMA (default) |
11.3 MB |
0.79 s |
1.52 s |
The stub’s cost is unpacking ~21 MB per run, which LZMA turns into
decompression time: on Linux with a warm page cache an uncompressed
stub build is nearly as fast, on Windows it is not. ZIP packaging
trades the smaller, compressed artifact for constant startup and no
disk writes at all.
-
--cosmo <path> (alias --cosmo-toolchain): Name the
Cosmopolitan Libc cosmocc
toolchain that builds the APE launcher stub from its C sources at
packaging time, overriding the automatic lookup. <path> is either
the cosmocc executable itself or the toolchain directory (one
containing bin/cosmocc, e.g. an unpacked
cosmocc.zip).
Notes:
- With
--cosmo-ruby, naming a toolchain explicitly is also how you
ask for the launcher stub instead of ZIP packaging (for the
extraction semantics: a real on-disk application directory, and
ARGV untouched by the interpreter’s option parser).
- When a toolchain is needed but not named,
--cosmo-ruby looks for
one in this order: the COSMOCC environment variable (the cosmocc executable
or its install directory), cosmocc in PATH, and finally the
conventional install locations ~/.cosmocc/*/bin/cosmocc,
~/cosmocc/*/bin/cosmocc, /opt/cosmocc/*/bin/cosmocc,
/opt/cosmo/bin/cosmocc and /usr/local/cosmocc/bin/cosmocc
(newest version first). If none is found the build stops with a
message naming all three mechanisms.
- Compiled stubs are cached in
~/.cache/ocran (keyed on the
toolchain and stub sources), so only the first build compiles.
- Given without
--cosmo-ruby, the packaged Ruby runtime is still
the host platform’s Ruby — the APE property then applies to the
launcher stub, not to the bundled application. See
docs/cosmocc-port-plan.md for status.
Native compilation (experimental):
Instead of packaging the interpreter, these options compile the program
ahead of time with Spinel, Matz’s Ruby
AOT compiler. The result is a native executable that needs no Ruby at all.
Spinel compiles a subset of Ruby (no eval of strings, no
method_missing, no runtime class building, only the standard library it
ships itself), so this works for some programs and not others. When it
does not, OCRAN tells you why.
-
--spinel: Compile script.rb with Spinel:
ocran app.rb --spinel # -> ./app (app.exe on Windows)
ocran app.rb --spinel --output myapp
The script is not run at build time. OCRAN scans the program statically
(the script, the files it requires, and the source of every gem it
requires) and passes Spinel the -I roots it needs for your lib/ and
for pure-Ruby gems. If Spinel cannot compile the program, OCRAN prints
the compiler’s error, then a report of what stands in the way, grouped
into your code and each gem. Gems with C extensions and standard
libraries Spinel does not provide are named as incompatible. If
spinel-doctor is installed next to the compiler, its report is shown
too. If Spinel is not installed, OCRAN explains how to install it and
still shows the report, so you can see whether installing it is worth
it. Use --spinel-opt <arg> (repeatable) to pass flags to the compiler,
for example --spinel-opt --int-overflow=promote or
--spinel-opt --defer-refusals. With --debug the binary is built
with -g. Only code is compiled in; data files have to ship next to
the executable.
Spinel compiles native code only from spin packages, not from gems
with C extensions. When the script is in a spin project (a spin.toml
in its directory or above, up to the repository root or your home
directory), OCRAN runs spin flags there and compiles with what it
prints: the dependencies’ -I roots, the objects of the C they carry
(--link) and --strict-require. A library a dependency provides is
then not reported, even where a gem of the same name has a C extension.
If a dependency has a native build step, allow it with
SPIN_ALLOW_NATIVE_BUILD=1 or spin trust <package>.
spin flags prints paths unquoted, so the project and its dependencies
must not be in a path that contains a space; OCRAN stops with the path
it could not find.
-
--roundhouse: Compile a Rails application into a native server
binary with Roundhouse, which
lowers the app to the Ruby subset Spinel compiles. OCRAN runs the
transpile, the generated project’s asset step (make assets, with
only the Gemfile’s assets group bundled) and spin build:
ocran --roundhouse path/to/rails/app # -> ./app-spinel/
The output is a directory (<app>-spinel by default, or --output /
--output-dir) that contains the binary plus the static/, public/,
db/ and config/ files it reads at run time, and a storage/ for
the SQLite database. On the first build the database is created from
db/seed.sql when the sqlite3 command is available. Rebuilding keeps
storage/. If Roundhouse does not cover the app yet, OCRAN shows the
useful parts of roundhouse check --continue: the gem census (which of
the app’s gems Roundhouse does not model), the first errors, and the
list of unsupported constructs. Pass flags to Roundhouse with
--roundhouse-opt <arg>, for example
--roundhouse-opt --survey --roundhouse-opt --allow-unsupported.
Installing the compilers. Neither is a gem. OCRAN looks for spinel,
spin and roundhouse in the SPINEL, SPIN and ROUNDHOUSE
environment variables (the command or the directory that contains it), then
in PATH, then in their usual install locations (~/.local/bin,
/usr/local/bin, ~/.cargo/bin). When one is missing, OCRAN prints how to
install it:
git clone https://github.com/matz/spinel && cd spinel
make deps && make && make install PREFIX=$HOME/.local
curl --proto '=https' --tlsv1.2 -LsSf \
https://github.com/rubys/roundhouse/releases/latest/download/roundhouse-installer.sh | sh
Apps compiled with Roundhouse also need the SQLite and jemalloc
development headers (libsqlite3-dev libjemalloc-dev, or
brew install sqlite jemalloc). OCRAN puts the directory pkg-config
reports for the allocator on LIBRARY_PATH for the build, so a Homebrew
jemalloc on Apple Silicon (under /opt/homebrew/lib, which the linker does
not search by default) links. The asset step needs Bundler, and Node.js
with npm when the app builds Tailwind.
Windows. WSL is the dependable way to use --spinel and --roundhouse
on Windows: both compilers work there as they do on Linux, and you get a
Linux binary. Spinel also builds natively with MinGW-w64 gcc, in
RubyInstaller’s Devkit (ridk enable) or an MSYS2 UCRT64 shell (see
Spinel’s docs/windows.md);
that port is community-maintained and best effort, and with it --spinel
produces a Windows .exe. Roundhouse’s Windows build is untested.
WebAssembly export (experimental):
--wasm exports the application as a web page that runs it in the browser.
The output is a folder (<scriptname>-wasm by default, or --output-dir)
or a zip archive (--output-zip, or an --output name that ends in
.zip). It contains index.html, the runtime and your program. The page
shows the program’s standard output and errors. Use the js library to
work with the page itself. Browsers only load WebAssembly over HTTP, so
serve the folder instead of opening the file:
ocran app.rb --wasm # -> app-wasm/
ocran app.rb --wasm=picoruby --output app.zip
python3 -m http.server -d app-wasm 8000 # then open http://localhost:8000
There are two runtimes:
--wasm (or --wasm=ruby): ruby.wasm,
CRuby compiled to WebAssembly, with its whole standard library (about
30 MB). It needs rbwasm from the ruby_wasm gem (gem install ruby_wasm;
OCRAN also uses RBWASM when it is set).
- OCRAN packs your files into the prebuilt interpreter from npm, which
takes seconds. Gems must be listed in the application’s Gemfile and
installed (
bundle install); pure-Ruby gems are packed in beside your
files, at /gems, and put on the load path in place of
bundler/setup, so require "bundler/setup" in your program is fine.
- Only when a gem has a C extension does OCRAN run
rbwasm build. Its
first run compiles CRuby and the gems for WebAssembly, which takes
several minutes, and is cached in ~/.cache/ocran/ruby_wasm. The
extensions are cross-compiled for WASI, and the ones that link system
libraries usually fail.
- The Ruby version follows the Ruby you run OCRAN with. Use
--wasm-ruby 3.4 to choose another one. Pass extra flags to
rbwasm build with --wasm-opt <arg>.
--wasm=picoruby (or --picoruby): PicoRuby,
the mruby-based Ruby for microcontrollers.
- Its runtime is about 2 MB, and nothing needs to be installed.
- PicoRuby has its own small library (
js, json, yaml, base64, …)
and no RubyGems. In the browser it cannot read your files, so OCRAN
bundles the program’s files into one script, in the order they are
required.
In both cases the script is not run at build time. OCRAN scans the program
and reports what may not work on the chosen runtime, grouped into your code
and each gem:
- gems the runtime cannot load;
- threads, processes, sockets and
gets;
- for PicoRuby, also CRuby standard libraries it does not have.
The build goes ahead anyway, since the program only fails if it reaches
those parts. The runtimes are downloaded from the npm registry once, checked
against the integrity hash the registry publishes, and cached in
~/.cache/ocran/npm.
Compilation:
- OCRAN runs your script (using
Kernel#load) and builds the output when it exits.
- Your program should
require all necessary files when invoked without arguments so OCRAN can detect all dependencies.
- DLLs are detected automatically; only those within your Ruby installation are included.
.rb files become console applications; .rbw files become windowed applications (without a console window popping up on Windows). Use --console or --windows to override.
Running your application:
- The working directory is not changed by OCRAN unless you use
--chdir-first
(extraction directory) or --chdir-exe-dir (directory containing the
executable). See “Working directory” below.
- When a
.exe is running, OCRAN_EXECUTABLE points to the .exe with its full path.
- The temporary location of the script is available via
$0.
- OCRAN does not set up the include path. Add
$:.unshift File.dirname($0) at the start of your script if you need to require additional files from the same directory as your main script.
Directory and zip output (Linux / macOS / Windows):
When using --output-dir or --output-zip, OCRAN produces the same file
layout as a .exe would extract to:
bin/ # Ruby interpreter and shared libraries
lib/ # Ruby standard library
gems/ # Bundled gems
src/ # Your application source files
script.sh # Launch script (Linux/macOS) — or script.bat on Windows
The launch script sets RUBYLIB, GEM_HOME, GEM_PATH, and any other
environment variables, then runs your script with the bundled Ruby.
On Linux/macOS, make the script executable and run it:
chmod +x myapp/script.sh
./myapp/script.sh
On Windows, run the batch file:
myapp\script.bat
Running as a Windows service
The self-extracting .exe, the wrapper .exe and the launch script all
start the packed ruby.exe as a child process. The Windows service control
manager accepts the service dispatcher only from the process it started
itself, so a service registered through any of them fails with error 1063
(“The service process could not connect to the service controller”).
Build with --output-dir (or --innosetup) instead and register the packed
interpreter directly, e.g. with sc create or the
win32-service gem’s
Win32::Service.create:
ocran service.rb --output-dir C:\MyService
sc create MyService binPath= "C:\MyService\bin\ruby.exe C:\MyService\src\service.rb"
That bare ruby.exe still gets the package’s environment: OCRAN packs a
RubyGems startup hook (lib/ruby/site_ruby/<version>/rubygems/defaults/operating_system.rb)
that sets GEM_HOME, GEM_PATH, RUBYLIB, SSL_CERT_FILE and the other
variables of the launch script to the directory’s actual location, unless
they are already set, clears those the launch script clears
(BUNDLE_GEMFILE), and then loads the Ruby installation’s own one
(RubyInstaller’s). OCRAN leaves the hook out, and warns, when the building
Ruby has such a file in its site_ruby already or keeps site_ruby outside
its installation directory; then set those variables in the service’s
environment yourself. The hook does not change the working directory (a service
starts in C:\Windows\System32), so find your files from __dir__. If the
script the launch script runs is a generated ocran-rubyopt-launcher.rb
(-I/-r in RUBYOPT), register that one.
OCRAN runs the script at build time, where the service’s mainloop cannot
work: skip it with defined?(Ocran) (see “Detecting OCRAN at build time”)
and require there what the service only loads later, such as net/http,
so that it gets packed.
Pitfalls:
- Avoid modifying load paths at runtime. Use
-I or RUBYLIB if needed, but don’t expect OCRAN to preserve them for runtime. OCRAN may pack sources into other directories than you
expect
- If you use
.rbw files or --windows, verify your application works with rubyw.exe before building.
- Avoid absolute paths in your code and when invoking OCRAN.
Multibyte path and filename support:
- OCRAN-built executables correctly handle multibyte paths (e.g. Japanese, emoji) on Windows 10 1903+.
- When using the executable from the console, run
chcp 65001 first to switch to UTF-8 on windows.
Limitations
OCRAN is not a cross-compiler. The executable or directory it produces bundles
the Ruby interpreter from the machine where OCRAN is run, so you must run
OCRAN on the same platform (and architecture) as the intended target:
- To produce a Windows
.exe, run OCRAN on Windows.
- To produce a Linux binary, run OCRAN on Linux.
- To produce a macOS app bundle, run OCRAN on macOS.
There is no support for building a Windows .exe from a Linux or macOS host,
or vice versa. If you need builds for multiple platforms, run OCRAN in CI on
each target platform separately (e.g., a Windows runner for .exe builds and
a Linux runner for Linux builds). See
Building for multiple platforms with GitHub Actions
for a ready-made setup.
Linux binary portability (glibc)
On Linux, OCRAN bundles the shared libraries your application loaded during
the build (libyaml, libssl, libcrypt, libgmp, libz, …) next to the bundled
Ruby, so the executable also runs on distributions where those libraries are
missing or have different sonames. It works with distro-packaged Ruby too
(e.g. dnf install ruby on Fedora), including its split gem layout and
rubypick wrapper.
One thing can never be bundled: glibc itself (and its dynamic loader).
Those always come from the target system, and glibc is only
backward-compatible. In practice:
- A Linux binary runs on any distribution whose glibc is at least as new
as the build machine’s.
- Build on the oldest distribution you want to support. For example, a
binary built on the oldest available
ubuntu-* GitHub runner runs on that
Ubuntu version and everything newer, while a binary built on a
cutting-edge distribution (e.g. fedora:latest) will not run on older
Debian/Ubuntu releases (version `GLIBC_2.4x' not found).
Use --no-autodll to disable shared library bundling.
Since OCRAN is not a cross-compiler, the recommended way to ship your app for
Windows, Linux, and macOS is a GitHub Actions matrix that runs OCRAN natively
on each platform. A minimal workflow:
name: Build binaries
on:
push:
tags: ['v*'] # build releases from version tags
workflow_dispatch: # allow manual runs
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- os: windows-latest # x86-64 Windows .exe
- os: ubuntu-22.04 # x86-64 Linux; oldest runner = widest glibc compatibility
- os: macos-14 # Apple Silicon macOS
- os: macos-15-intel # Intel macOS
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4'
bundler-cache: true # if your app has a Gemfile
- run: gem install ocran
# Run OCRAN on your entry script. Add "-- <args>" if your script needs
# arguments to exit cleanly during the dependency-detection run.
- run: ocran myapp.rb --output myapp
# produces myapp.exe on Windows, myapp on Linux/macOS
- uses: actions/upload-artifact@v4
with:
name: myapp-${{ matrix.os }}
path: myapp*
Notes:
- Pick the oldest
ubuntu-* runner GitHub offers for the Linux build so
the binary runs on as many distributions as possible (see
Linux binary portability).
- On macOS, each architecture needs its own build:
macos-14 (and newer
numbered ARM runners) produce Apple Silicon binaries, macos-15-intel
produces Intel binaries.
- Swap the
ocran invocation for --output-dir, --output-zip,
--macosx-bundle, or --innosetup depending on how you want to ship
(see Recommended usage).
- For tag pushes you can attach the artifacts to a GitHub release with a
follow-up job (e.g.
softprops/action-gh-release).
Requirements
- Ruby 3.3+
- For building Windows
.exe: Windows with RubyInstaller DevKit (mingw-w64), or Wine on Linux/macOS. An mswin Ruby (built with Visual C++, see mswin Ruby) works as well.
- For building Linux and MacOS binaries: the respective build tools
- For
--output-dir / --output-zip: any platform with Ruby 3.3+
- For
--output-zip on Linux/macOS: the zip command must be available
- For
--output-zip on Windows: PowerShell (included in Windows 8+)
Output architecture
The architecture of the generated executable matches the Ruby interpreter used to run OCRAN:
-
macOS (Intel / Apple Silicon) — The output binary targets the same CPU as your Ruby installation. If you build with an ARM64 Ruby (Apple Silicon), the result is an ARM64 executable and will not run on Intel Macs. Build on Intel (or with an Intel Ruby under Rosetta) to produce a universally compatible x86-64 binary.
-
Windows on ARM (Windows 11 ARM) — RubyInstaller recently started shipping ARM64 builds; Installing the ARM64 RubyInstaller on a Windows ARM machine and running OCRAN from it will produce an ARM64 .exe. These run on ARM Windows natively. Installing the standard x86-64 RubyInstaller on a Windows ARM machine and running OCRAN from it will (probably?) produce an x86-64 .exe. These run on ARM Windows via the built-in x86-64 emulation layer, so the executables work on both ARM and x86-64 Windows targets. If you use --no-lzma, note that lzma.exe (the bundled compressor) is also x86-64 and relies on the same emulation.
mswin Ruby (Visual C++)
OCRAN also packages with an mswin Ruby (x64-mswin64_140), the Ruby built
with Microsoft Visual C++ instead of MinGW, e.g. the official builds from
https://cache.ruby-lang.org/pub/ruby/binaries/mswin64/ or
ruby/setup-ruby with ruby-version: mswin. There is no MSYS2 devkit:
- The source gem (and
rake build in a checkout) compiles the stubs with
nmake -f src/Makefile.mswin, so run it from a Visual Studio developer
prompt (vcvars64.bat, Build Tools with the C++ workload), as for any
native gem on mswin. The stubs link the C runtime statically.
- The Ruby DLL of an mswin Ruby links the Visual C++ runtime
(
vcruntime140.dll), which is not part of Windows: without the
VC++ Redistributable
ruby.exe cannot start. OCRAN bundles the VC++ runtime DLLs next to the
packed ruby.exe (app-local deployment), so the executable runs on a
machine without the Redistributable.
- The libraries an mswin Ruby uses from vcpkg (gmp, libffi, OpenSSL,
libyaml, zlib) live next to
ruby.exe. OCRAN reads the import tables of
ruby.exe, the Ruby DLL and the packed extensions and bundles the DLLs
they need from there, even with --no-autodll (as it packs RubyInstaller’s
ruby_builtin_dlls).
- If the packed interpreter still cannot load a DLL, the executable says so
(
The Ruby interpreter could not start: a DLL it needs was not found)
instead of exiting silently with status 0xC0000135.
Development
Quick start
git clone https://github.com/largo/ocran.git
cd ocran
bin/setup # install Bundler & all dev gems, build stubs
bundle exec rake # run the full Minitest suite
exe/ocran filename.rb # build filename.rb as an executable
Developer utilities (bin/ scripts)
| Script |
Purpose |
bin/setup |
Installs Bundler and all required development gems, then builds stub.exe |
bin/console |
Launches an IRB console with OCRAN preloaded |
Rake tasks
| Task |
Purpose |
rake build |
Compile stub(.exe) (requires mingw-w64 + DevKit, MSVC with an mswin Ruby, or Unix build tools) |
rake clean |
Remove generated binaries |
rake test |
Execute all unit & integration tests |
Technical details
OCRAN first runs the target script to detect files loaded at runtime (via
Kernel#require and Kernel#load).
For .exe output, OCRAN embeds everything into a single executable: a C stub,
and a custom opcode stream containing instructions to create directories,
extract files, set environment variables, and launch the script. The stub
extracts everything to a temporary directory at runtime and runs the script.
For --output-dir / --output-zip, OCRAN performs the same file collection
but writes directly to the filesystem and generates a shell/batch launch
script instead of an opcode stream.
Libraries
Any code loaded through Kernel#require when your script runs is included.
Conditionally loaded code is only included if it is actually executed during
the OCRAN build run.
Otherwise, OCRAN won’t know about it and will not include
the source files.
You can use defined?(OCRAN) to check if the script is running while OCRAN is building it and exit the script after dependencies are loaded but before the main logic runs.
RubyGems are handled specially: when a file from a gem is detected, OCRAN
includes the required files from that gem. It does not automatically include all the files of the Gem, which could be required at runtime. This behavior is controlled with
the --gem-* options.
Libraries found in non-standard path (for example, if you invoke OCRAN
with “ruby -I some/path”) will be placed into the site dir
(lib/ruby/site_ruby). Avoid changing $LOAD_PATH or
$: from your script to include paths outside your source
tree, since OCRAN may place the files elsewhere when extracted into the
temporary directory.
If your script uses Kernel#autoload, OCRAN will attempt to load those
constants so they are included in the output. Missing modules are ignored
with a warning.
Dynamic link libraries are detected and included by OCRAN: .dll files on
Windows (for example WxWidgets), and on Linux the non-glibc shared libraries
the process loaded (libyaml, libssl, libcrypt, …), which are placed next to
the bundled Ruby with appropriate soname symlinks (see
Linux binary portability). Disable with
--no-autodll.
Including libraries non-automatically
If automatic dependency resolution is insufficient, use --no-dep-run to
skip running your script. This requires --gem-full and typically
--add-all-core.
You can specify gems via a Bundler Gemfile with --gemfile. OCRAN includes
all listed gems and their dependencies (they must be installed, not vendored
via bundle package).
Example — packaging a Rails app without running it:
ocran someapp/script/rails someapp --output someapp.exe --add-all-core \
--gemfile someapp/Gemfile --no-dep-run --gem-full --chdir-first -- server
Note the space between -- and server! It’s important; server is
an argument to be passed to rails when the script is ran.
Gem handling
By default, OCRAN includes all scripts loaded by your script plus important
non-script files from those gems, excluding C/C++ sources, object files,
READMEs, tests, and specs.
Four modes:
- minimal: Loaded scripts only
- guess: Loaded scripts and important files (DEFAULT)
- all: All scripts and important files
- full: All files in the gem directory
If files are missing from the output, try --gem-all=gemname first, then
--gem-full=gemname. Use --gem-full to include everything for all gems.
Using OCRAN under bundle exec
OCRAN loads your script inside its own process to find out what it depends
on, so the bundle OCRAN itself runs under is the bundle that dependency run
sees. That matters as soon as the two are not the same.
Running bundle exec ocran app.rb requires ocran in the application’s
Gemfile. This is Bundler’s rule, not OCRAN’s: bundle exec refuses to run
a command the bundle does not contain (“ocran is not currently included in
the bundle”). Add gem "ocran" to the Gemfile, or install OCRAN with gem install ocran and call ocran without bundle exec. Be aware that every
gem the Gemfile lists is packed into the application when you build with
--gemfile, OCRAN included.
From the application’s own directory it just works. bundle exec ocran app.rb, with or without --gemfile Gemfile, packages the application
against its own bundle - including gems declared with path: or gemspec,
which exist nowhere but that Gemfile.
Packaging one project from inside another project’s bundle needs
--gemfile. If the bundle you are in is not the application’s, pass
--gemfile path/to/app/Gemfile. It governs the dependency run as well as
the gem list, so a require "bundler/setup" in your script sets up the
application’s bundle and not the one you happen to be standing in. Without
it the script is loaded under the wrong bundle and usually dies with a
LoadError for one of its own gems; OCRAN warns when it can see that this
is what you are doing.
Gems that the surrounding bundle merely activated are not packed. The
contents are decided by the application’s own Gemfile and by what the
dependency run actually loads, so building a small application from inside a
large development bundle does not drag that bundle along.
The packaged executable is independent of Bundler. It carries its own
gems and its own Gemfile, and it clears the variables through which Bundler
hands a bundle to a child process (BUNDLER_SETUP, BUNDLE_GEMFILE,
BUNDLE_LOCKFILE, RUBYOPT), so it runs correctly even when started from a
bundle exec shell, from a Rakefile, or from another Ruby program.
Exception: executables built with --cosmo-ruby cannot do that. There
the cosmopolitan Ruby is the executable, so its RubyGems has already acted
on BUNDLER_SETUP before any packed code can run, and the application
aborts with Bundler::GemNotFound over gems of the bundle it was launched
from. Start such an executable outside a bundle, or clear the variables
first - Bundler.with_original_env { system("./app.com") } from Ruby, or
env -u BUNDLER_SETUP -u BUNDLE_GEMFILE ./app.com from a shell. Building
with --cosmo-ruby under bundle exec is fine; only launching the result
from inside a bundle is not.
Code-signing a macOS app bundle
After building with --macosx-bundle, sign the bundle with your Developer ID:
codesign --deep --force --verify --verbose \
--sign "Developer ID Application: Your Name (TEAMID)" \
MyApp.app
Verify the signature:
codesign --verify --deep --strict --verbose=2 MyApp.app
spctl --assess --type execute --verbose MyApp.app
For distribution outside the Mac App Store, notarize with Apple:
# Submit for notarization (requires app-specific password or API key)
xcrun notarytool submit MyApp.app \
--apple-id [email protected] \
--team-id TEAMID \
--password APP_SPECIFIC_PASSWORD \
--wait
# Staple the notarization ticket so it works offline
xcrun stapler staple MyApp.app
Requirements:
- Xcode Command Line Tools (
xcode-select --install)
- An Apple Developer account with a “Developer ID Application” certificate in Keychain
Creating a Windows installer
To make your application start faster or keep files between runs, use
--innosetup to generate an Inno Setup installer.
Install Inno Setup 5+ and add it to your PATH, then supply an .iss script:
Make sure that iss is in the PATH environment variable by running the command iss in your terminal.
Do not add any [Files] or [Dirs] sections
to the script; Ocran will figure those out itself.
To continue the Rails example above, let’s package the Rails application
into an installer. Save the following as someapp.iss:
[Setup]
AppName=SomeApp
AppVersion=0.1
DefaultDirName={pf}\SomeApp
DefaultGroupName=SomeApp
OutputBaseFilename=SomeAppInstaller
[Icons]
Name: "{group}\SomeApp"; Filename: "{app}\someapp.bat"; IconFilename: "{app}\someapp.ico"; Flags: runminimized;
Name: "{group}\Uninstall SomeApp"; Filename: "{uninstallexe}"
ocran someapp/script/rails someapp --output someapp.exe --add-all-core \
--gemfile someapp/Gemfile --no-dep-run --gem-full --chdir-first --no-lzma \
--icon someapp.ico --innosetup someapp.iss -- server
If all goes well, a file named “SomeAppInstaller.exe” will be placed
into the Output directory.
Environment variables
OCRAN clears the RUBYLIB environment variable before running your script so it does not pick up load
paths from the end user’s Ruby installation.
OCRAN sets the RUBYOPT environment variable to the value it had when you invoked OCRAN. For .exe
output, OCRAN_EXECUTABLE is set to the full path of the running executable:
ENV["OCRAN_EXECUTABLE"] # => C:\Program Files\MyApp\MyApp.exe
Working directory
By default the OCRAN executable does not change the working directory when it
starts. Two opt-in build options change this:
--chdir-first: the working directory is always the common parent
directory of your source files inside the extraction directory. Do not use
this if your application takes filenames as command-line arguments.
--chdir-exe-dir: the working directory is the directory that contains the
executable itself. Use this when your application reads or writes files that
are placed next to the .exe (config files, spreadsheets, output folders,
…) using relative paths. Note that relative filenames passed as
command-line arguments will then also resolve against the executable’s
directory instead of the invoker’s current directory.
Without these options, you should not assume anything about the current
working directory when your executable is invoked. It can be the directory
where the executable is placed (when invoked through the Windows Explorer),
the users’ current working directory (when invoking from the Command Prompt),
or even C:\\WINDOWS\\SYSTEM32 when the executable is invoked through a file
association.
To require additional files from the source directory while keeping the
user’s working directory:
$LOAD_PATH.unshift File.dirname($0)
Finding files next to the executable
Be aware that __FILE__, __dir__ and $0 inside a packaged application
point to the extracted copy of your script in the temporary extraction
directory — not to the directory containing the .exe. Anchoring paths on
__dir__ (e.g. APP_ROOT = File.expand_path(__dir__)) therefore makes the
application look for its data files inside the temporary directory, which is
usually not what you want.
To locate files relative to the executable, either build with
--chdir-exe-dir and use plain relative paths, or anchor your paths on the
OCRAN_EXECUTABLE environment variable, which is always set to the full path
of the running executable:
APP_ROOT = if ENV["OCRAN_EXECUTABLE"]
File.dirname(ENV["OCRAN_EXECUTABLE"])
else
__dir__ # plain `ruby myapp.rb` during development
end
Detecting OCRAN at build time
Check for the Ocran constant to detect whether OCRAN is currently building
your script:
app = MyApp.new
app.main_loop unless defined?(Ocran)
Additional files and resources
Append extra files, directories, or glob patterns to the command line:
ocran mainscript.rb someimage.jpeg docs/document.txt
ocran script.rb assets/**/*.png
This produces the following layout in the output (temp dir for .exe,
or the output directory for --output-dir):
src/mainscript.rb
src/someimage.jpeg
src/docs/document.txt
Both files, directoriess and glob patterns can be specified on the
command line. Files will be added as-is. If a directory is specified,
OCRAN will include all files found below that directory. Glob patterns
(See Dir.glob) can be used to specify a specific set of files, for
example:
ocran script.rb assets/**/*.png
Command Line Arguments
Pass arguments to your script (both during the build run and at runtime)
after a -- marker:
ocran script.rb -- --some-option=value
Extra arguments supplied by the user at runtime are appended after the
compile-time arguments.
Load path mangling
Adding paths to $LOAD_PATH or $: at runtime is not recommended. Adding
relative load paths depends on the working directory being the same as where
the script is located (see above). If you have additional library files in
directories below the directory containing your source script, use this idiom:
$LOAD_PATH.unshift File.join(File.dirname($0), 'path/to/script')
Window/Console
By default, OCRAN builds console applications from .rb files and windowed
applications (without a console window) from .rbw files.
Ruby on Windows provides two executables: ruby.exe is a console mode
application and rubyw.exe is a windowed application that does not bring up
a console window when launched from Windows Explorer. By default, or if
--console is used, OCRAN uses the console runtime. OCRAN automatically
selects the windowed runtime when your script has the .rbw extension, or
when you pass --windows.
If your application works in console mode but not in windowed mode, first
check that your script works without OCRAN using rubyw.exe. A script that
prints to standard output (puts, print, etc.) will eventually raise an
exception under rubyw.exe once the IO buffers fill up.
You can also wrap your script in an exception handler that logs errors to a
file:
begin
# your script here
rescue Exception => e
File.open("except.log", "w") do |f|
f.puts e.inspect
f.puts e.backtrace
end
end
Packaging a Rails application
A Rails application with a SQLite database packages into a single
executable that serves HTTP. test/test_rails.rb builds one from scratch
on every run (rails new, bin/rails generate scaffold, plus controllers
and views written on the fly), packages it and drives a full CRUD round
trip through the resulting binary; read it as the worked example. It is
opt-in — run it with OCRAN_RAILS_TEST=1 ruby -Itest test/test_rails.rb.
Write a small entry script next to config/ (Rails’ own config.ru is
for a Rack server, not for OCRAN) and point OCRAN at it together with the
directories Rails reads at run time:
ocran server.rb app config db public --no-autoload --gem-all
Four things are worth knowing before you try it.
--no-autoload is required. OCRAN’s autoload walker sweeps every
Module in ObjectSpace and tries to const_get each autoloaded
constant. Under Rails that means dragging in I18n::Tests,
Prism::Translation and everything else the framework declares but never
loads — minutes of output ending in an error. In production Rails eager
loads the application itself, so the walker has nothing to contribute.
--gem-all is required. Dependency detection is $LOADED_FEATURES
based, and Rails reads a great deal it never requires. The first thing
to break without it is activesupport/lib/active_support/locale/en.rb,
which I18n reads as a data file during boot. For the same reason the
application’s own app, config, db and public directories have to
be named on the command line: ERB templates, database.yml, locale files
and migrations are not required and so are invisible to the dependency
run.
Gems Rails declares but never loads still have to be inside. OCRAN
packs the gemspec of every gem it detects, and RubyGems activates the
complete declared dependency graph of a gemspec, not just the code you
actually load. activesupport declares minitest and drb, railties
declares rake; a running server loads none of them, so nothing puts them
in the package, and the executable then dies at startup with
Gem::MissingSpecError. Require them from the entry script:
begin
gem "minitest", "~> 5.0" # 5.x has no dependencies of its own
rescue Gem::LoadError
end
require "minitest" # activesupport
require "drb" # activesupport
require "rake" # railties
To find the equivalent list for your own application, boot it and diff the
declared dependencies against what is loaded:
Gem.loaded_specs.each_value do |spec|
spec.runtime_dependencies.each do |dep|
puts "#{dep.name} </args></version></arg></scriptname></arg></app></package></arg></path></path></toolchain></ruby></lib></gem></archive></runtime-dir></file></level></value></id></x></x></value></key></str></ico></file></appname></id></scriptname></file></dir></scriptname></scriptname></file></file></dllname></script></other></ruby>
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论