在Ruby中,如何验证一个Struct的身份?

In Ruby, how does one verify the identity of a Struct?

我一直在努力理解 Ryan Bates 在他的 Presenters RailsCast (#287 Presenters from Scratch (pro) - RailsCasts) 中使用的 present 方法中 self 的 class。在视频中,Ryan 说 'Self is the template object which has all the helper methods we want to access',但我想知道这个对象的 class。在阅读了一系列博客文章、SO 线程和 Ruby 文档之后,我开始认为 self 是一种结构,但我不知道如何证实这个想法。

我的问题是:1)在下面的present方法中,selfStruct吗?2) 如何验证某物是一个结构体?

module ApplicationHelper
  def present(object, klass = nil)
    klass ||= "#{object.class}Presenter".constantize
    presenter = klass.new(object, self)
    yield presenter if block_given?
    presenter
  end
end

我问这个是因为我没有太多使用 Struct classes 的经验,当我在上面的方法中间坚持 binding.pry 并尝试获取 self 的 class 的名称,我最终有更多问题。

这个 post 有助于解释 Struct 的工作原理,但没有解释如何确认他们拥有一个 Struct。

最初,当我开始剖析 present 方法时,我发现这个 answer 很有用。但是,我被评论抛弃了,说 "ModelPresenter is initialized by passing the model, and the ApplicationHelper class",因为 ApplicationHelper 是一个模块。

总结:

使用is_a?(Struct)

说明:

结构是匿名的构造函数class:

struct_class = Struct.new(:foo)
# => #<Class:0x007fa7e006ea98>

您可以检查匿名 class 的实例是否是这样的结构:

inst = struct_class.new
inst.class.superclass
# => Struct

但是 Object#is_a? 检查父 class 以及 superclasses:

inst.is_a?(Struct)
# => true

您可以在以下任意示例中看到相同的行为:

# inherits from String
anon_class = Class.new(String) 

inst = anon_class.new
# => ""

inst.class == String
# => false

inst.is_a?(String)
# => true