Last active
October 25, 2015 16:11
-
-
Save hrom512/ed1acd559a802d17bda8 to your computer and use it in GitHub Desktop.
Presenters from http://habrahabr.ru/post/266761/
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(model) | |
| return if model.blank? | |
| klass = "#{model.class}Presenter".constantize | |
| presenter = klass.new(model, self) | |
| yield(presenter) if block_given? | |
| presenter | |
| 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
| class BasePresenter < Delegator | |
| attr_reader :model, :h | |
| alias_method :__getobj__, :model | |
| def initialize(model, view_context) | |
| @model = model | |
| @h = view_context | |
| end | |
| def inspect | |
| "#<#{self.class} model: #{model.inspect}>" | |
| 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
| class PostPresenter < BasePresenter | |
| def to_link | |
| h.link_to model.to_s, model | |
| end | |
| def content | |
| h.markdown model.content | |
| end | |
| # оборачиваем связь | |
| def comments | |
| model.comments.map { |comment| h.present comment } | |
| 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
| - @posts.each do |post| | |
| .post | |
| - present(post) do |post_presenter| | |
| h2 = post_presenter.title | |
| = post_presenter.content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment