Skip to content

Instantly share code, notes, and snippets.

@johnbintz
Created September 21, 2012 14:45
Show Gist options
  • Save johnbintz/3761886 to your computer and use it in GitHub Desktop.
Save johnbintz/3761886 to your computer and use it in GitHub Desktop.
Simple Presenter pattern in ~30 lines of code.
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