Gem pretty_ancestors: 打印包含层级的 ancestors 信息

mizuhashi · April 28, 2017 · Last by mizuhashi replied at May 02, 2017 · 1375 hits

ruby 使用 mixin 的时候是直接 copy 到原型链的,ancestors 返回的是一维数组,于是尝试了一下用 ancestors 还原出 include 和 prepend 的结构,调试的时候可以用到。

安装:

gem install pretty_ancestors

例子:

module M1
  include (Module.new{})
end

module M2
  include M1
end

module M3
end

module M4
  prepend M3
end

module M5
end

class C
  include M4
  include M2
  prepend M5
end

pp C.pretty_ancestors
# =>
# [[[M5], C, [[M2, [[M1, [#<Module:0x00000000f546f0>]]]], [[M3], M4]]],
#  [Object,
#   [PP::ObjectMixin, Kernel]],
#  BasicObject]

pp C.pretty_ancestors(:raw)
# =>
# [[[[[], M5, []]],
#   C,
#   [[[], M2, [[[], M1, [[[], #<Module:0x00000000f546f0>, []]]]]],
#    [[[[], M3, []]], M4, []]]],
#  [[], Object, [[[], PP::ObjectMixin, []], [[], Kernel, []]]],
#  [[], BasicObject, []]]

在 raw 数据中每个模块 M 都被表示为[[*prepended], M, [*included]],普通输出则是去掉了所有[]的简化。对于 Class,pretty_ancestors 的第一维是继承链上的类。

C.pretty_ancestors.flatten 总是等于 C.ancestors,所以可以直接按顺序确定优先级。

github: https://github.com/CicholGricenchos/pretty_ancestors

另求 pretty_print 调教经验。。

1 Floor has deleted

有具体点的信息吗?

Reply to mizuhashi

不知道你的具体问题嘛(当然我没怎么折腾过这个),AR 的 PP 代码定义在这 https://github.com/rails/rails/blob/master/activerecord/lib/active_record/core.rb#L513-L535 就是打印模型数据用的

哦 好像我最开始的表述有误,删掉了。。。单纯说 PP 的使用,可以看下 AR 的,他是可以嵌套打印内部数据的

Reply to jasl

嗯,我看看

You need to Sign in before reply, if you don't have an account, please Sign up first.