我一直在试图理解Ryan Bates在他的Presenters RailsCast (#287 Presenters from Scratch (pro) - RailsCasts)中使用的
我的问题是:1) 在下面的
present
方法中的self
类。在视频中,Ryan说,“Self是模板对象,具有我们想要访问的所有帮助器方法”,但我想知道这个对象的类。阅读了一系列博客文章、SO线程和Ruby文档后,我开始认为self
是一种Struct,但我不知道如何确认这个概念。我的问题是:1) 在下面的
present
方法中,self
是一个Struct吗?2) 如何验证某个东西是否是Struct?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
类的经验。当我在上述方法中插入binding.pry
并尝试获取self
的类名时,我会遇到更多问题。
- When I enter
self.class
, I get,#<Class:0x007fb64f696268>
I wondered if gettingClass
here might indicate that I have aStruct
, but I couldn't find any documentation that confirmed this - When I enter
self.class.class
, I getClass
When I enter
self
, I get an extensive object that starts with the lines of code of code listed below@ line 16 ApplicationHelper#present: 14: def present(object, klass = nil) 15: klass ||= "#{object.class}Presenter".constantize 16: binding.pry 17: presenter = klass.new(object, self) 18: yield presenter if block_given? 19: end [1] pry(#<#<Class:0x007fb64f696268>>)> self => #<#<Class:0x007fb64f696268>:0x007fb64f6948f0 @_assigns={"marked_for_same_origin_verification"=>true}, @_config={}, @_controller= #<PostsController:0x007fb64f6762d8 @_action_has_layout=true, @_action_name="show", @_config={}, @_db_runtime=0, @_lookup_context= #<ActionView::LookupContext:0x007fb64f6760d0 @cache=true, @details= {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby]}, @details_key=#<Concurrent::Map:0x007fb64f697938 entries=0 default_proc=nil>, @prefixes=["posts", "application"], @rendered_format=:html, @view_paths= #<ActionView::PathSet:0x007fb64f675fe0
这篇文章在解释Struct的工作原理方面非常有帮助,但没有解释如何确认自己是否有一个Struct。
起初,当我开始分析present
方法时,发现这个答案很有帮助。然而,我被评论中说“ModelPresenter是通过传递模型和ApplicationHelper类来初始化”的说法所困扰,因为ApplicationHelper是一个模块。