获取有关Crystal中继承链的信息

时间:2017-08-25 22:02:08

标签: ruby inheritance reflection metaprogramming crystal-lang

出于好奇并想了解一点Crystal的一般结构,我正在寻找一些反射功能,这些功能可以让我更好地理解继承链是如何构建的。

我在想像ruby的superclassancestorsincluded_modules方法。

Crystal语言中是否有这样的东西?

此外,有一些图表可以让我看到全局。

1 个答案:

答案 0 :(得分:5)

使用macros实现Crystal中的元编程。

  

宏是在编译时接收AST节点并生成粘贴到程序中的代码的方法。

Crystal已经有superclassancestors的实现,它们在编译时返回结果。所以你可以这样做:

is returned when i visited these url with

为方便起见,要检查继承,您可以编写自己的宏。考虑到学习目的,它可能看起来像这样:

pp({{ MyClass.superclass }})
pp({{ MyClass.ancestors }})

然后你可以做检查:

class Class
  def superclass
    {{ @type.superclass }}
  end

  def ancestors
    {% if @type.ancestors.size > 0 %}
      {{ @type.ancestors }}
    {% else %}
      [] of Nil
    {% end %}
  end

  def included_modules
    {% if @type.ancestors.any? { |a| a.class.stringify.ends_with?(":Module") } %}
      {{ @type.ancestors.select { |a| a.class.stringify.ends_with?(":Module") } }}
    {% else %}
      [] of Nil
    {% end %}
  end

  def inheritance_chain
    String.build do |chain|
      cls = self
      chain << cls
      while !(cls = cls.superclass).nil?
        chain << " > #{cls}"
      end
    end
  end
end

如果你走得更远:

class A
end

module B
end

require "crystal/system/random"

class C < A
  include B
  include Crystal::System::Random
end

C.name             # => "C"
C.superclass       # => A
C.ancestors        # => [Crystal::System::Random, B, A, Reference, Object]
C.included_modules # => [Crystal::System::Random, B]
A.included_modules # => []

现在使用C.superclass # => A C.superclass.try &.superclass # => Reference C.superclass.try &.superclass.try &.superclass # => Object C.superclass.try &.superclass.try &.superclass.try &.superclass # => nil

inheritance_chain