DEV Community

kojix2
kojix2

Posted on

7 3

πŸ’Ž `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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay