Last active
August 29, 2015 14:10
-
-
Save ottodranik/6ea0ded9fca29c67fa51 to your computer and use it in GitHub Desktop.
This is how add and use presenters in Rails
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
<% projects.each do |project| %> | |
<% cache [project, current_locale] do %> | |
<% present project do |project_presenter| %> | |
<li class="container project"> | |
.... | |
<div class="activities-overview"> | |
<ol class="activities"> | |
<%= project_presenter.show_categories %> | |
</ol> | |
</div> | |
<div class="bar"> | |
<div class="graph"> | |
<%= project_presenter.show_categories_bar %> | |
</div> | |
</div> | |
.... | |
</li> | |
<% end %> | |
<% end %> | |
<% end %> | |
<%= paginate projects %> |
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
class ProjectPresenter | |
NUMBER_OF_ACTIVITIES = 4 | |
attr_reader :template | |
def initialize(project, template) | |
@project = project | |
@template = template | |
end | |
def show_categories | |
template.render partial: "category", | |
collection: categories_with_remainder, | |
locals: { project: @project } | |
end | |
def show_categories_bar | |
template.render partial: "categories_bar", | |
as: :category, | |
collection: categories_with_remainder, | |
locals: { project: @project } | |
end | |
private | |
def sorted_categories | |
@project.sorted_categories | |
end | |
def categories_with_remainder | |
categories = sorted_categories | |
if sorted_categories.length > NUMBER_OF_ACTIVITIES + 1 | |
categories = sorted_categories.take(NUMBER_OF_ACTIVITIES) | |
remaining_categories = sorted_categories.drop(NUMBER_OF_ACTIVITIES) | |
categories << RemainingCategory.new(remaining_categories) | |
end | |
categories | |
end | |
end |
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
module ApplicationHelper | |
.... | |
def present(object, klass = nil) | |
klass ||= "#{object.class}Presenter".constantize | |
presenter = klass.new(object, self) | |
yield presenter if block_given? | |
presenter | |
end | |
..... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment