Rails演示者教程中的方法问题
关于我在本教程中看到的几种方法的问题: https : //richonrails.com/articles/rails-presenters
特别是:
module ApplicationHelper def present(model, presenter_class=nil) klass = presenter_class || "#{model.class}Presenter".constantize presenter = klass.new(model, self) yield(presenter) if block_given? end end
和
class BasePresenter < SimpleDelegator def initialize(model, view) @model, @view = model, view super(@model) end def h @view end end
本方法如何工作? 我对它的参数参数非常困惑,即model, presenter_class=nil
以及整个方法。
我也对model, view
参数以及哪里/什么是super(@model)
方法感到困惑?
任何可以解释这些方法的信息都会非常有用,因为我一直在盯着它,同时想知道它们是如何起作用的。
我会试一试。
本方法接受两个参数,模型和演示者类。
presenter_class = nil
表示presenter_class
是可选参数,如果在调用方法时未将该变量作为参数传递,则将设置为nil
。
我在代码中添加了注释,以便逐步解释发生了什么。
# Define the Helper (Available in all Views) module ApplicationHelper # Define the present method, accepts two parameters, presnter_class is optional def present(model, presenter_class=nil) # Set the presenter class that was passed in OR attempt to set a class that has the name of ModelPresenter where Model is the class name of the model variable klass = presenter_class || "#{model.class}Presenter".constantize # ModelPresenter is initialized by passing the model, and the ApplicationHelper class presenter = klass.new(model, self) # yeild the presenter if the rails method block_given? yield(presenter) if block_given? end end
这是解释收益率如何运作的另一个问题
以下是有关rails constantize方法的更多信息
BasePresenter
inheritance自SimpleDelegator类(文档) 。
class BasePresenter < SimpleDelegator def initialize(model, view) # Set the instance variables @model and @view as the two parameters passed to BasePresenter.new @model, @view = model, view # calls the inherited SimpleDelegator initializer with the @model parameter super(@model) end # An instance method that returns the @view variable that was set on initialization def h @view end end