Skip to content

Instantly share code, notes, and snippets.

@bspaulding
Forked from ajvargo/gist:1277150
Created October 11, 2011 14:51
Show Gist options
  • Save bspaulding/1278287 to your computer and use it in GitHub Desktop.
Save bspaulding/1278287 to your computer and use it in GitHub Desktop.
Create a presenter object on the fly in Rails
# Inspired by Ryan Bates pro RailsCast "Presenters from Scratch"
# This is a proof of concept for 'automagically' creating presenter objects
#
# This assumes you have presenter objects that follow the convention
# Object => ObjectPresenter
#
# It intercepts the 'render' method in the controller, and does some
# introspection to see if there is a presenter defined for the class
# of the instance variable being looked at. If so, it makes a presenter
# and adds it as an instance variable
#
class ApplicationController < ActionController::Base
protected
alias_method_chain :render, :presenters
def render_with_presenters(options = nil, deprecated_status = nil, &block)
self.instance_variables.reject {|iv_sym| iv_sym[1] == "_" }.each do |iv_sym|
instance_variable = self.instance_variable_get iv_sym # value of @foo
iv_class = instance_variable.class.to_s # Person
presenter_class = "#{iv_class}Presenter"
if Object.const_defined? presenter_class
self.instance_variable_set("@#{iv_sym}_presenter".to_sym, presenter_class.constantize.send(:new, instance_variable))
end
end
# call the ActionController::Base render to show the page
render
end
end
class ActionPresenter::Base
def self.inherited(base)
@children << base
end
def self.presents(*args)
end
end
class FooPresenter < ActionPresenter::Base
presents :singular_class_name # SingularClassName class
# presents AClassObject
# presents lambda {|object| true } # Returns true if can present object.
# presents [:alist, :of, AnyOne, lambda {|object| true }]
end
ActionPresenter::Base.presenters_for(object)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment