Created
March 9, 2012 01:52
-
-
Save mgreenly/2004579 to your computer and use it in GitHub Desktop.
presenter ideas
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(subject, klass = nil) | |
| klass ||= "#{subject.class}Presenter".constantize | |
| presenter = klass.new(subject, 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 CommentPresenter < Presenter::Base | |
| def sensitive_attribute | |
| full_monty ? @subject.sensitive_attribute : "censored" | |
| end | |
| private | |
| def full_monty | |
| context.current_user == self.author | |
| 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
| <% present @post do |post| %> | |
| <%= post.sensitive_attribute %> | |
| <% post.present_each_comment do |comment| %> | |
| <%= comment.sensitive_attribute %> | |
| <% 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 < Presenter::Base | |
| def sensitive_attribute | |
| full_monty ? @subject.sensitive_attribute : "censored" | |
| end | |
| def present_each_comment | |
| self.comments.each do |comment| | |
| yield CommentPresenter.new(comment, context) if block_given? | |
| end | |
| end | |
| private | |
| def full_monty | |
| context.current_user == self.author | |
| 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
| require 'delegate' | |
| class Presenter::Base < SimpleDelegator | |
| def initialize(subject, context) | |
| @subject, @context = subject, context | |
| super(@subject) | |
| end | |
| def method_missing(sym, *args, &block) | |
| subject.send(sym, *args, &block) | |
| end | |
| protected | |
| def subject | |
| @subject | |
| end | |
| def context | |
| @context | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment