DEV Community

kojix2
kojix2

Posted on

πŸ’Ž `eval` in Crystal language! Anyolite πŸŸ’πŸ”΄ is amazing...

There is no eval in the Crystal language.

If you had to use eval in the Crystal language, you would have to embed Crystal itself in your executable.

Eval is often regarded as a bad practice in Ruby language. But sometimes, I want to use eval in Crystal language. At that time, I found a great project that makes it possible to execute eval even in the Crystal language by including mruby (or CRuby) into the Crystal executable.

Anyolite

https://github.com/Anyolite/anyolite

Have you ever heard of anyolite? It is a ruby embedded in a crystal. I think it is a perfect name for this library.

I tried it

shards.yml

dependencies:
  anyolite:
    github: Anyolite/anyolite
Enter fullscreen mode Exit fullscreen mode

When you run shards install, Anyolite automatically prepares mruby for you.

kitty.cr

require "anyolite"

code = ARGV[0]

class Kitty
  def initialize(@n : Int32)
  end

  def mew
    puts "mew " * @n
  end
end

Anyolite::RbInterpreter.create do |rb|
  Anyolite.wrap(rb, Kitty)
  Anyolite.eval(code)
  p Anyolite.cast_to_crystal(rv, Int32)
end
Enter fullscreen mode Exit fullscreen mode

build:

crystal build kitty.cr
Enter fullscreen mode Exit fullscreen mode

run:

./kitty "Kitty.new(n: 3).mew; 6"
Enter fullscreen mode Exit fullscreen mode

output:

mew mew mew 
6
Enter fullscreen mode Exit fullscreen mode

You can see that the Ruby code is being evaluated at run time. Finally, I found a way to run eval in the Crystal language!

The size of the generated executable is about 7 Mb, which is a bit large because of the mruby integration. However, running eval with Crystal is exciting and well worth it.

Reference

https://anyolite.github.io/anyolite/Anyolite.html

https://github.com/Anyolite/anyolite/wiki

Top comments (0)