roc/examples/ruby-interop
2023-06-10 15:04:25 -04:00
..
platform merge main 2023-06-10 15:04:25 -04:00
.gitignore Add initial examples/ruby-interop 2022-08-11 17:15:07 -04:00
demo.c remove all definitions of roc_memcpy 2023-06-02 15:23:05 -07:00
extconf.rb Add initial examples/ruby-interop 2022-08-11 17:15:07 -04:00
main.roc roc format 2022-11-04 15:44:18 -04:00
README.md Rename some Ruby interop demo things 2022-11-03 23:04:15 -04:00

Ruby Interop

This is an example of calling Roc code from Ruby.

Installation

To run this example, you will need these to be installed already (in addition to Roc):

  • ruby version 2.7.6 or later
  • clang version 11.0.0 or later
  • make version 4.0 or later

Make sure you have the right versions of Ruby and Clang especially! This example won't work with earlier versions.

Building the Roc library

First, cd into this directory and run this in your terminal:

roc build --lib

This compiles your Roc code into a binary library in the current directory. The library's filename will be libhello plus an OS-specific extension (e.g. libhello.dylib on macOS).

Generating the Makefile

Next, run this: (remember that you need Ruby 2.7.6 or higher - otherwise later steps will fail!)

ruby extconf.rb

This generates a Makefile. (There are only two Roc-specific lines in extconf.rb; they are both commented.) You only need to do this step once; now that you have the Makefile, you can use it along with roc build to rebuild from now.

Building the Ruby Library from the Roc Library

Finally, run this:

make

This uses the Makefile generated earlier to take the compiled Roc library and combine it with demo.c to generate a Ruby library.

Try it out!

You can now try this out in Ruby's REPL (irb), like so:

$ irb
irb(main):001:0> require_relative 'demo'
=> true
irb(main):002:0> RocApp::call_roc 42
=> "The number was 42, OH YEAH!!! 🤘🤘"

Rebuilding after Changes

To rebuild after changing either the demo.c file or any .roc files, run:

roc build --lib && make -B

The -B flag is necessary when you only change .roc files, because otherwise make thinks there's no work to do and doesn't bother rebuilding.

About this example

This was created by following a tutorial on Ruby C extensions and some documentation (along with more nicely formatted, but potentially out-of-date docs).

The mkmf ("make makefile") method in extconf.rb generates a Makefile, which can then be run (using make with no arguments) to generate a compiled library that Ruby knows how to import via require or require_relative.