【问题标题】:Questions on Methods from Rails Presenters TutorialRails Presenters 教程中关于方法的问题
【发布时间】:2016-07-16 06:55:13
【问题描述】:

关于我在本教程中看到的几个方法的问题: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 方法是如何工作的?我对它的 arguments 参数感到很困惑,即model, presenter_class=nil 以及整个方法。

我也对model, view 参数感到非常困惑,super(@model) 方法在哪里/是什么?

任何可以解释这些方法的信息都会非常有帮助,因为我过去一直在盯着它看,同时想知道它们到底是如何工作的。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我会试一试。

    present 方法接受两个参数,一个模型和一个演示者类。

    presenter_class = nil 表示presenter_class 是一个可选参数,如果在调用方法时没有将变量作为该参数传递,则将其设置为nil

    我在代码中添加了 cmets 来逐步解释发生了什么。

    # 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
    

    Here's another question explaining how yield works

    Here's some more info on the rails constantize method

    BasePresenter 继承自 SimpleDelegator 类 (documentation)

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多