module Rubellite::Docs::A_GETTING_STARTED::QUICKSTART

Overview

Quickstart Guide & Usage Patterns

This guide provides hands-on code examples for embedding Rubellite into your Crystal project, evaluating Ruby scripts, calling Ruby methods with arguments, and executing blocks.

Executive Summary & Key Topics

Topic Method / Anchor Description
Evaluating Scripts & Invoking Methods .topic_01_eval_and_methods Running code strings and dispatching methods dynamically with zero boilerplate.

Related Guides & Source References

Defined in:

rubellite/docs/a_getting_started/quickstart.cr

Class Method Summary

Class Method Detail

def self.topic_01_eval_and_methods : Nil #

Evaluating Scripts & Invoking Methods: Running code strings and dispatching methods dynamically with zero boilerplate.

Rubellite offers high-level helpers on the Ruby (or Rubellite) module and rich ergonomics on Rubellite::Value. Initialization is completely automatic: calling Ruby.eval, accessing Ruby["Constant"], or invoking .to_ruby boots the VM seamlessly on demand.

API Method Target Description
`Ruby.eval(code)` Global Parses and executes a Ruby code string (auto-inits VM)
`Ruby[const_name]` Global Resolves a top-level Ruby constant (e.g. `Ruby["JSON"]`)
`Ruby[const_name]?` Global Safely resolves a constant, returning `nil` if undefined
`value.call(method, *args)` Object Invokes a method with protected SEH execution
`value.call?(method, *args)` Object Safe call returning `nil` if an exception occurs
`value.dig(*keys)` Collection Safe nested key retrieval across Hashes and Arrays
`value.each(&blk)` Collection Yields elements to a Crystal block
`Rubellite.export(name, &blk)` Global Exposes a Crystal Proc directly to Ruby as `Rubellite.`

Working Examples

require "rubellite"

# Auto-initialization: No explicit Rubellite.init needed!
json = Ruby["JSON"]
parsed = json.call("parse", %({"name": "Rubellite", "tags": ["crystal", "ruby"]}))

# Safe nested navigation (interchangeably handles Symbol and String keys)
puts parsed.dig("tags", 0).try(&.to_s) # => "crystal"

# Bidirectional Crystal function export
Rubellite.export("add_numbers") do |args|
  (args[0].to_i64 + args[1].to_i64).to_ruby
end

result = Ruby.eval("Rubellite.add_numbers(19, 23)")
puts result.to_i64 # => 42

Common Pitfalls & Safety Caveats

  • Warning: Ruby exceptions raised in eval or call are wrapped into Crystal Rubellite::Error exceptions preserving backtraces.
  • Warning: CRuby allows only one initialization per OS process. Automatic initialization manages this safely.

Frequently Asked Questions (FAQ)

  • Q: How do I catch Ruby errors in Crystal? A: Rescue Rubellite::Error — it preserves the Ruby exception class name, message, and backtrace.

[View source]