Would it be possible to transpile Crystal => Ruby?

I’m thinking about rewriting my Ruby on Rails application in Crystal with the Lucky web framework. It looks really awesome!

I’m just a bit concerned about not having access to a REPL (e.g. irb and rails console). I also read this Medium post about the long compilation times.

I’ve done some research and have read through a lot of threads and posts, including the following wiki pages / issues:

  • GH Wiki: Crystal for Rubyists
  • GH #681: Can we have a builtin REPL?
  • GH #914: Differences from Ruby?

I was wondering if it might be possible to transpile Crystal code to Ruby? Then I would be able to run a Crystal program with a REPL and try out some different things at run-time. The transpiler could also add Sorbet type annotations and enable run-time checks to get type-safety.

The main thing I’m worried about is debugging code at run-time (although it doesn’t look too bad.) But it would be really nice if I had the option to run the code as plain Ruby, so I could define new methods and try things out in a REPL whenever I need to debug something.

I’m also worried about not having access to rails console in production. I guess I will need to make sure that I can do everything from my admin dashboard, write a custom CLI tool to perform some operations, or just write some plain SQL queries.

Amber has a REPL and there is icr.

I dont know about having a Crystal to Ruby transpiler. I think Crystal has diverged enough that you would end up with quiet a few edge cases. You might be able to write a Crystal to Ruby binding layer. There has been a few Crystal Ruby bridges. I think you might be able to have a Ruby REPL that drives a Crystal program though a bridge.

2 Likes

You wouldn’t run a Crystal program, but a Ruby program. Although transpiled from Crystal, it’s still a Ruby program and wouldn’t differ from a native Ruby program.
Crystal and Ruby have completely diverse runtimes. Just considering one is compiled the other interpreted, but also a heck of other differences.
So this would essentially lead not to a REPL for Crystal, but only to a new way to write Ruby applications (i.e. in Crystal). I doubt there’d be much value in that.

Instead, I’d suggest to reconsider your workflows that are based on a REPL. Because Crystal is compiled the compiler does a lot of stuff you don’t get with Ruby. You probably won’t need a REPL as much for debugging and similar purposes. The compiler already helps you a lot with that (type checking etc.). Also embracing a more test driven behaviour would move your interactive test sessions to formalized and repeatable specs.

For inspections into running systems where you would use rails console, you could either use a CLI tool or just individual Crystal programs that execute from a single file using crystal run. In both cases the workflow is captured in code, and not in a transient console session.

2 Likes