Skip to content

Instantly share code, notes, and snippets.

@unders
Created November 26, 2010 15:05
Show Gist options
  • Save unders/716821 to your computer and use it in GitHub Desktop.
Save unders/716821 to your computer and use it in GitHub Desktop.
Presenter that works with Rails
#app/presenters/article_presenter
module ArticlePresenter
def fancy_name
end
end
#app/presenters/comment_presenter
module CommentPresenter
def fancy_name
end
def body
body # shows the complete body text on the show page
end
end
#app/presenters/comment_index_presenter
module CommentIndexPresenter
def author
end
def body
attributes['body'] # shows a shorter version of the body text on the index page
end
end
#app/presenters/other_comment_presenter
module OtherCommentPresenter
def fancy_name
end
end
#app/presenters/statistic_presenter
module StatisticPresenter
def ranking
(attributes['ranking'] == 0) ? nil : attributes['ranking']
end
def profit
"%.f" % attributes['profit'].round
end
end
#app/helpers/presenter_helper
module PresenterHelper
def present_each (collection, presenter_module = nil)
collection.each do |resource|
presenter_module ||= "#{resource.class}Presenter".constantize
yield resource.extend(presenter_module)
end
end
end
#app/controllers/articles
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id]).extend(ArticlePresenter)
end
#app/views/articles/show
<% present_each(@article.comments) do |comment| %>
<%= comment.fancy_name %>
<% end %>
<% present_each(@article.comments, OtherCommentPresenter) do |comment| %>
<%= comment.fancy_name %>
<% end %>
#app/views/articles/index
<% present_each(@articles) do |article| %>
<%= article.fancy_name %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment