关于我在本教程中看到的几种方法的问题: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
present
方法如何运作?我对其参数参数感到困惑,即model, presenter_class=nil
以及整个方法。
我也对model, view
个参数非常困惑,以及super(@model)
方法在哪里/什么?
任何可以解释这些方法的信息都会非常有用,因为我一直盯着它过去,同时想知道它们是如何起作用的。
答案 0 :(得分:0)
我会试一试。
present
方法接受两个参数,一个模型和一个presenter类。
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
。
我已经在代码中添加了评论,以便逐步解释发生了什么。
BasePresenter
Here's another question explaining how yield works
Here's some more info on the rails constantize method
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
继承自SimpleDelegator类(documentation)。
@interface NSString (ObjCFlagTesting)
-(void) myLibName_TestLinkerFlag;
@end
@implementation NSString (ObjCFlagTesting)
-(void) myLibName_TestLinkerFlag {}
@end