Skip to content

Instantly share code, notes, and snippets.

@myobie
Created May 19, 2011 17:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/981251 to your computer and use it in GitHub Desktop.
Save myobie/981251 to your computer and use it in GitHub Desktop.
My try at a good presenter pattern with rails
module ApplicationHelper
def present(model, items = {})
name = model.is_a?(String) ? model : model.class.model_name.underscore
items.merge!(name.to_sym => model) unless model.is_a?(String)
"#{name.classify}Presenter".constantize.new(controller, items) do |presenter|
yield(presenter) if block_given?
end
end
end
class ApplicationPresenter
include ActionView::Helpers
include Rails.application.routes.url_helpers
class << self
delegate :model_name, :to => :model
end
def self.model
@model ||= model_klass
end
def self.model_klass
self.name.gsub(/Presenter/, '').constantize
end
attr_reader :controller
def initialize(con, items = {})
@controller = con
items.each do |item_name, item|
send(:"#{item_name}=", item)
end
yield(self) if block_given?
end
end
<ul>
<% @posts.each do |post_model| %>
<% present(post_model) do |post| %>
<li><%= post.title_link %></li>
<% end %>
<% end %>
</ul>
class PostPresenter < ApplicationPresenter
attr_accessor :post
delegate :id, :to_param,
:to => :post
def title_link
raw link_to(h(post.title), post)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment