As the application grows, I’m starting to use a Presenter Pattern similar to what’s outlined here:
http://blog.jayfields.com/2007/03/rails-presenter-pattern.html
I would like the presenter to be able to access the same scope of the controller it’s in, in a way that minimally impacts application performance, and that has a clear API. Something like this:
class UsersController < ApplicationController
def index
@view = UsersPresenter.new(self)
end
end
class Presenter
def initialize(controller)
end
end
class UsersPresenter < Presenter
end
I could use method_missing to access methods on the controller but that comes at a performance cost, and would probably be confusing to debug:
class Presenter
attr_reader :controller
def initialize(controller)
@controller = controller
end
def method_missing(method, *args, &block)
controller.send(method, *args, &block)
end
end
I would like it to work just like a module, but without being a module so I don’t clutter the global controller namespace.
Any ideas what’s best here? Maybe the delegate method?
Thanks for the tips.
An approach to work around
method_missing: Enumerate all instance methods of the controller and define methods in the eigenclass of your presenter (in the initializer). However I doubt that it’s better performance-wise when compared tomethod_missing.Also this won’t work for methods that were added to the controller via
method_missing(like polymorphic routes).I don’t think that you can work around the
method_missingcompletely if you want access to all the (missing) methods of the controller without explicitly writingcontroller.some_methodin your presenter.