Created
May 19, 2011 17:11
-
-
Save myobie/981251 to your computer and use it in GitHub Desktop.
My try at a good presenter pattern with 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
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 |
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
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 |
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
<ul> | |
<% @posts.each do |post_model| %> | |
<% present(post_model) do |post| %> | |
<li><%= post.title_link %></li> | |
<% end %> | |
<% end %> | |
</ul> |
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
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