Skip to content

Instantly share code, notes, and snippets.

@ottodranik
Last active August 29, 2015 14:10
Show Gist options
  • Save ottodranik/6ea0ded9fca29c67fa51 to your computer and use it in GitHub Desktop.
Save ottodranik/6ea0ded9fca29c67fa51 to your computer and use it in GitHub Desktop.
This is how add and use presenters in Rails
<% 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 %>
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
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