Skip to content

crystal-china/meta

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

meta

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

Installation

dependencies:
  meta:
    github: crystal-china/meta

Then:

require "meta"

Usage

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_methods
Foo.subclasses
Foo.all_subclasses
Foo.class_methods
Foo.constants
Foo.ancestors
Foo.includers

all_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_methods

output.png

Direct File Usage

You 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.

Notes

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.

Contributors

About

Print methods of Class/Object etc for Crystal

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors