Adding rails runner to AdonisJS
I’ve been toying with AdonisJS quite a bit lately. For the past 10 years, Rails has been my framework of choice. Adonis has almost everything I’m used to in Rails. One thing I found missing is a script runner command, i.e. the equivalent for rails runner.
Why is this needed?
A common script I add to every Rails project is a “release” script that is triggered on deploy.
It’d look something like this:
# usage: rails runner scripts/release.rb
# Sync static data from code to DB
StaticDataSyncer.run!
# Create a release on Sentry
SentryReleaseNotifier.run!
There’s zero boilerplate here.
AdonisJS’s closest equivalent for this is custom commands, but those require far more boilerplate. Here’s what the release script above would look like as a custom command:
import { BaseCommand } from '@adonisjs/core/ace'
export default class ReleaseCommand extends BaseCommand {
static commandName = 'release'
static description = 'Run actions after deploy'
async run() {
// Sync static data from code to DB
await StaticDataSyncer.run!
// Create a release on Sentry
await SentryReleaseNotifier.run!
}
}
In this small example, there’s 9 lines of noise vs. 4 lines of code that’s useful to the reader.
Note: This is a slightly unfair comparison, the true Rails equivalent is probably rake tasks, which have a similar level of boilerplate.
What’s the solution?
I solved this by adding a run command that does exactly what rails runner does. The script can now look exactly like the Ruby version above, zero boilerplate!
// usage: node ace run scripts/release.ts
// Sync static data from code to DB
await StaticDataSyncer.run!
// Create a release on Sentry
await SentryReleaseNotifier.run!
This might feel like a pointless optimization to some, but small touches like this are what make frameworks like Rails/Laravel a pleasure to work with 🙂
adonis-run is on GitHub if you’d like to give it a try!