Compile-time introspection helpers for Crystal.
meta exposes information from Crystal's macro system as ordinary Crystal values. It can list
methods, class methods, subclasses, ancestors, constants, instance variables, and superclass
chains.
This shard is based on an idea shared by Ary Borenszweig in this Crystal forum thread: https://forum.crystal-lang.org/t/print-out-the-instance-methods-defined-class-or-the-path-where-the-current-class-is/4771/2
dependencies:
meta:
github: crystal-china/metaThen:
require "meta"class Foo
def hello(name : String) : Nil
end
end
Foo.methods
# => [def hello(name : String) : Nil]Foo.new.methods
Foo.new.instance_vars
Foo.new.superclass
Foo.new.superclasses
Foo.new.all_methodsFoo.subclasses
Foo.all_subclasses
Foo.class_methods
Foo.constants
Foo.ancestors
Foo.includersall_methods returns methods grouped by the class or module they come from:
Foo.new.all_methods
# => Hash(String, Array(Crystal::Meta::AbstractMethod))Use awesome_print for readable output:
require "awesome_print"
require "./src/meta"
class Foo
def foo; end
end
module Baz
def baz; end
end
class Bar < Foo
include Baz
def bar; end
end
ap! Bar.new.all_methodsYou can also paste src/meta.cr into a file at compile time:
{{ read_file("/path/to/meta.cr").id }}This is useful when you want the helpers locally without adding a shard dependency.
These helpers rely on Crystal macro metadata, so they are mostly useful at compile time and may not behave like runtime reflection in dynamic languages.
See spec/meta_spec.cr for more examples.
- Ary Borenszweig
- Billy.Zheng vil963@gmail.com
