0

Question about a couple of methods that I saw in this tutorial: https://richonrails.com/articles/rails-presenters

In particular:

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

And

class BasePresenter < SimpleDelegator 
    def initialize(model, view)
        @model, @view = model, view
        super(@model)
    end

    def h 
        @view 
    end

end

How does the present method work? I'm pretty confused about its arguments parameters, ie, model, presenter_class=nil along with the whole method.

And I'm also very confused about model, view arguments as well, and where/what is super(@model) method?

Any information that can explain those methods would be so immensely helpful because I've been staring at it for the past while wondering how the heck they work.

user273072545345
  • 1,536
  • 2
  • 27
  • 57

1 Answers1

0

I'll give this a shot.

The present method accepts two parameters, a model, and a presenter class.

The presenter_class = nil means that presenter_class is an optional parameter, and will be set to nil if a variable is not passed as that parameter when the method is called.

I've added comments to the code to explain what's happening step by step.

# 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

The BasePresenter inherits from the SimpleDelegator class (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
Michael Brawn
  • 303
  • 2
  • 9