Created
September 21, 2012 14:45
-
-
Save johnbintz/3761886 to your computer and use it in GitHub Desktop.
Simple Presenter pattern in ~30 lines of code.
This file contains hidden or 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
require 'delegate' | |
class Presenter < SimpleDelegator | |
def self.model_name | |
@_model_name ||= ActiveModel::Name.new(self.name.gsub('Presenter', '').constantize) | |
end | |
def self.for(objects) | |
objects.collect { |item| (item.class.name + "Presenter").constantize.new(item) } | |
end | |
attr_reader :original | |
def initialize(original) ; @original = original ; end | |
def __getobj__ ; @original ; end | |
def to_model ; self ; end | |
# this doesn't have to be Rails-specific, should be usable w/ Sinatra w/ a few tweaks | |
module ViewHelpers | |
def render_presenter(object, *args) | |
render Presenter.for(object), *args | |
end | |
end | |
ActionView::Base.send(:include, Presenter::ViewHelpers) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment