Crystal

After its 0.24.1 release a week ago I decided to give Crystal a whirl. It’s been around since 2014 but is gaining traction.

I started my programming journey hacking on PHP in 2001 and grew into a developer with Ruby and its clean syntax. I’ve dabbled in Go but didn’t care for the syntax. I’ve dabbled in Elixir but had a hard time getting my app deployed with the right Erlang/OTP dependencies. Crystal ticks most of the boxes I care about:

  • Clean, familiar syntax
  • Fast!
  • Easy compilation to a single, easily-deployable binary
  • Modern standard library
  • Nice documentation

As its slogan says: “Fast as C, slick as Ruby.”

It also has a mature Sinatra-like web mini-framework called Kemal and an incubating-by-Rails-consultancy-juggernaut-Thoughtbot framework called Lucky which is shaping up nicely.

Getting Started

Installing Crystal on Mac is pretty easy with Homebrew: brew install crystal-lang.

Here’s a simple Hello World app:

puts "Hello World"

Run with crystal run hello-world.cr or build a binary with crystal build hello-world.cr.

The syntax is identical to Ruby in most simple cases, but it’s not Ruby. For example, it can have types:

class Person
  def initialize(name : String)
    @name = name
    @age = 0
  end

  def name
    @name
  end

  def age
    @age
  end
end

kevin = Person.new("Kevin")
kevin.name #=> "Kevin"

Sinatra vs. Kemal

I coded up a quick Sinatra “Hello World” app (which I can do mostly from memory) and a similar one in Kemal to give you a flavor of what it’s like to get started in Crystal.

Sinatra

require "sinatra"

get "/" do
  "Hello World!"
end

Now let’s run and benchmark it:

% RACK_ENV=production ruby sinatra.rb # run
% wrk -c16 -t16 -d30s http://localhost:4567/ # benchmark
Running 30s test @ http://localhost:4567/
  16 threads and 16 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     6.41ms    7.87ms 178.16ms   91.30%
    Req/Sec   177.17     38.21   303.00     71.07%
  63540 requests in 30.09s, 11.21MB read
Requests/sec:   2111.50
Transfer/sec:    381.50KB

Kemal

require "kemal"

get "/" do
  "Hello World!"
end

Kemal.run

(Looks familiar, eh?) Let’s (compile!), run, and benchmark:

% crystal build kemal.cr --release # compile
% ./kemal # run
% wrk -c16 -t16 -d30s http://localhost:3000/ # benchmark
Running 30s test @ http://localhost:3000/
  16 threads and 16 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.69ms    9.52ms 223.64ms   94.47%
    Req/Sec     1.34k   291.21     1.89k    71.22%
  639215 requests in 30.04s, 73.76MB read
Requests/sec:  21280.90
Transfer/sec:      2.46MB

About an order-of-magnitude faster! (Don’t you just love a good microbenchmark?) Plus we didn’t have to sacrifice any of the clean, familiar syntax of Ruby.

Crystal in Crystal

As I dove deeper, I learned Crystal is (mostly) implemented in Crystal, especially its standard library. (Kind of like Rubinius, remember that?) And its a modern one with built-in JSON parsing and generation support and a nice HTTP client, for example.

Since things are just ramping up the barrier of entry to contributing to Crystal and its fledgling libraries is pretty low. Especially since you don’t have to write C to contribute.

Growing Crystal

I’m skeptical about Crystal’s long term future, and probably won’t use it for any client apps at the moment, but I am digging into it for side projects and starting to advocate for it in small areas where is makes sense in the hopes that it may one day get the support it needs to grow.

TIL: Running Tests in VS Code

Since I’ve started using Visual Studio Code (still seems weird to say that…) I’ve been looking for a way to easily run tests. Today I learned how you can easily run tasks in Code in the integrated terminal.

Configure Task

First, choose the TasksConfigure Tasks menu. Code has a bunch of pre-built ones, but we just want to run a shell command so choose Others.

Use a configuration task like the following:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "taskName": "Run tests",
      "type": "shell",
      "command": "rails",
      "args": [
        "${relativeFile}"
      ],
      "group": "test",
      "presentation": {
        "reveal": "always",
        "panel": "new"
      }
    }
  ]
}

See that ${relativeFile} bit? There’s a bunch of variables you can put there:

  • ${workspaceRoot} the path of the folder opened in VS Code
  • ${workspaceRootFolderName} the name of the folder opened in VS Code without any slashes (/)
  • ${file} the current opened file
  • ${relativeFile} the current opened file relative to workspaceRoot
  • ${fileBasename} the current opened file’s basename
  • ${fileBasenameNoExtension} the current opened file’s basename without the extension
  • ${fileDirname} the current opened file’s dirname
  • ${fileExtname} the current opened file’s extension
  • ${cwd} the task runner’s current working directory on startup
  • ${lineNumber} the current selected line number in the active file

Imagine setting up tasks to run your entire suite (e.g. rails test), the current file (rails test ${relativeFile}), the current line (rails test ${relativeFile}:${lineNumber}), etc.

Now running this task (with ⌘R and selecting the task) will popup the integrated terminal and run the task.

Bonus tip: ⌘-Click files and files with line numbers to jump directly to that file and line in Code. Super handy.

Keyboard Shortcut

Now that we have our task, we can setup a keyboard shortcut to run it easily. I setup ⌘R to run tests like so:

{
  "key": "cmd+r",
  "command": "workbench.action.tasks.runTask",
  "args": "Run tests",
}

Spotify Volume Control with Hammerspoon

One of Spotify’s best features is its ability for a client to become a remote to another version of itself running on a different device. A few months ago I started using the Mac app on my laptop to control the speakers connected to a PC in my office.

Everything works pretty well, except for the volume. Out of habit, I would use the volume keys on my Mac to adjust the volume only to change the system volume and not affect Spotify at all. After probably 600 times of doing this I decided to fix it.

Hammerspoon to the rescue! (For those not in the know, Hammerspoon allows you to write Lua scripts to control your Mac with a really great “standard library” of functions to control things like window positions, volume, running AppleScript, etc.)

With this little bit of code in my ~/.hammerspoon/init.lua file I can use:

  • F7 to goto the previous song
  • F8 to play/pause Spotify only (sometimes iTunes or something would randomly launch before)
  • F9 to skip to the next song
  • F11/F12 to adjust the volume of Spotify if playing, otherwise adjust the system volume
-- Remap media keys to Spotify-priority equivalents
hs.hotkey.bind({}, "f7", function()
  hs.spotify.previous()
end)

hs.hotkey.bind({}, "f8", function()
  hs.spotify.playpause()
end)

hs.hotkey.bind({}, "f9", function()
  hs.spotify.next()
end)

hs.hotkey.bind({}, "f11", function()
  playing = hs.spotify.isPlaying()

  if playing then
    hs.spotify.volumeDown()
  else
    output = hs.audiodevice.defaultOutputDevice()
    output:setVolume(output:volume() - 10)
  end
end)

hs.hotkey.bind({}, "f12", function()
  playing = hs.spotify.isPlaying()

  if playing then
    hs.spotify.volumeUp()
  else
    output = hs.audiodevice.defaultOutputDevice()
    output:setVolume(output:volume() + 10)
  end
end)

You have to change the Keyboard System Preferences to intrepret the top row as F1, F2, etc. instead of Brightness, Volume, etc.) I picked F7 through F12 so the markings on the keys matched the functionality.

Of course, this may all be irrelevant with the Magic Toolbar