Module: BasePresenter::ControllerMethods::ClassMethods

Defined in:
app/presenters/base_presenter.rb

Instance Method Summary collapse

Instance Method Details

#expose_presenters(*names) ⇒ void

This method returns an undefined value.

Exposes data objects to the view layer via their designated presenters.

Example:

class StationController < ApplicationController
  expose_presenters :station, :stations
end

This defines two (helper-)methods station and stations, that look up @station and @stations and convert them to presenter objects.

Parameters:

  • names (Array<String, Symbol>)

    names of the to-be-created methods


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'app/presenters/base_presenter.rb', line 197

def expose_presenters(*names)
  if names.empty?
    class_name = to_s.split('::').last.gsub(/Controller$/, '')
    collection_name = class_name.underscore
    resource_name = collection_name.singularize
    names = [resource_name, collection_name]
  end

  names.each do |name|
    define_method name do
      cached = instance_variable_get("@#{name}__presenter")
      if cached
        cached
      else
        obj = instance_variable_get("@#{name}")
        return if obj.nil?
        cached = if obj.is_a?(Array) || obj.is_a?(ActiveRecord::Relation)
          obj.map(&:to_presenter)
        else
          obj.to_presenter
        end
        instance_variable_set("@#{name}__presenter", cached)
      end
    end
    helper_method name
  end
end