Status: Alpha

This builder takes in a Ruby program that defines a singular HTTP handler and outputs it as a serverless function.

When to Use It

Whenever you want to expose an API or a function written in Ruby.

How to Use It

Define a index.rb file inside a folder as follows:

require 'cowsay'

Handler = Proc.new do |req, res|
    res.status = 200
    res['Content-Type'] = 'text/plain'
    res.body = Cowsay.say('hello world', 'cow')
end

Inside Gemfile define:

source "https://rubygems.org"

gem "cowsay", "~> 0.3.0"

And define a now.json like so:

{
  "version": 2,
  "builds": [{ "src": "*.rb", "use": "@now/ruby" }]
}

Rack Interface

Many Ruby frameworks interface with Rack for forwarding HTTP requests to web applications written in Ruby. You can use Rack with frameworks such as Sinatra or Rails.

Instead of defining a handler, write the application as usual, like this Sinatra application:

require 'sinatra'

get '/*' do
    'Hello world'
end

Inside Gemfile define:

source "https://rubygems.org"

gem "sinatra", "~> 2.0"
gem "rack", "~> 2.0"

Add a Rack config file at index.ru to start the application:

require './app'

run Sinatra::Application

And define a now.json like so:

{
  "version": 2,
  "builds": [{ "src": "index.ru", "use": "@now/ruby" }]
}

Using Rack with Rails

Rails creates a Rack config file config.ru in the root directory of the Rails project. Use this file in now.json and map the routes to that destination:

{
  "version": 2,
  "builds": [{ "src": "config.ru", "use": "@now/ruby" }],
  "routes": [{ "src": "(.*)", "dest": "config.ru" }]
}

Most frameworks use their own implementation of routing. However, you can use a catch-all route to circumvent the framework and instead use the Now Routing Layer to match a route to a serverless function.

Technical Details

Entrypoint

The entrypoint file must be a .rb source file with one of the following variables defined:

  • Handler proc that matches the do |req, res| signature
  • Handler class that inherits from the WEBrick::HTTPServlet::AbstractServlet class

Alternatively, a .ru Rack config file will serve the Ruby application it contains.

Version

Ruby 2.5.3 is used.

Dependencies

This builder supports installing dependencies defined in the Gemfile. Alternatively, dependencies can be vendored with the bundler install --deployment command (useful for gems that require native extentions). In this case, dependencies are not built on deployment.