Introspection(and its alternatives) in Crystal

In Ruby, it is very helpful to use introspection methods(like #constants) to discover new APIs.

By analogy, I tried the same in Crystal, with this example:

require "gobject/gtk/autorun"

window = "AccelGroup", border_width: 20)
window.connect "destroy", ->Gtk.main_quit
window.add"Press Ctrl+S")

accel_group =
accel_group.connect(Gdk::KEY_S, :control_mask, :zero_none) do
  puts "Ctrl+S pressed!"

p! Gdk.constants

But it failed to compile with:

| p! Gdk.constants                                               
Error: undefined method 'constants' for Gdk:Module

I intended to find out what other combinations besides Ctrl+S(Gdk::KEY_S) are there.

I wonder, in similar situations, what do you use for introspection in Crystal?

There still is introspection, but it’s not available at runtime. You could try like {% pp Gdk.constants %}. Although the more conventional way to do it (maybe not applicable in this context) is to leverage the generated API docs. This gives you something like Crystal 1.8.0-dev, but for a particular project. These are ideally hosted by the shard to make it easy to explore. However given this particular shard relates to generating bindings to C libs, your best bet would be finding the docs for that lib. E.g. Gdk – 3.0.

EDIT: One thing to keep in mind is .constants will include both actual constants and types within that namespace.

Somewhat related: Print out the instance methods defined class? or the path where the current class is?


Thank you!