Skip to content

Instantly share code, notes, and snippets.

@vladfaust
Created January 20, 2019 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladfaust/cfd4f9302c674b187cf3ece37f2f37b8 to your computer and use it in GitHub Desktop.
Save vladfaust/cfd4f9302c674b187cf3ece37f2f37b8 to your computer and use it in GitHub Desktop.
Get all ancestors and descendants including modules in Crystal
# https://carc.in/#/r/620u
module Foo
end
module Bar
include Foo
end
class Baz
include Bar
end
abstract struct Qux
include Bar
end
struct Quux < Qux
end
class X(T)
def initialize
{% puts "descendants or self (modules + objects):" %}
{% for type in Class.all_subclasses.select { |t| t.instance <= T}.map(&.instance) %}
{% pp type %}
{% end %}
{% puts "ancestors (modules + objects):" %}
{% for type in (Class.all_subclasses.select { |t| t.instance > T && !(t.instance <= Object) }.map(&.instance) + Object.all_subclasses.select { |t| t > T && (t < Reference || t < Struct) }).uniq %}
{% pp type %}
{% end %}
end
end
X(Qux).new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment