Created
October 11, 2011 02:50
-
-
Save ajvargo/1277150 to your computer and use it in GitHub Desktop.
Create a presenter object on the fly in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
def render(options = nil, deprecated_status = nil, &block) | |
self.instance_variables.each do |iv_sym| | |
next if iv_sym[0] == "@" && iv_sym[1] == "_" | |
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 | |
presenter = presenter_class.constantize.send(:new, instance_variable) | |
# following defines the presenter variable name as class_presenter | |
# you may want to use the instance variable name directly, so you can have | |
# current_user_presenter and user_presenter, ie. | |
self.instance_variable_set "@#{iv_class.tableize.singularize}_presenter".to_sym, presenter | |
end | |
end | |
# call the ActionController::Base render to show the page | |
super | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment