Last active
October 11, 2019 23:55
-
-
Save Odaeus/92a9f78df479ffa9bd09 to your computer and use it in GitHub Desktop.
Simple Presenter Pattern
This file contains 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 ApplicationController < ActionController::Base | |
# ... | |
concerning :Presenters do | |
included do | |
helper_method :present | |
end | |
def present(record_or_array, klass) | |
if record_or_array.respond_to?(:map) | |
record_or_array.map {|item| klass.new(item, view_context) } | |
else | |
klass.new(record_or_array, view_context) | |
end | |
end | |
end | |
end |
This file contains 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
# /app/presenters/article_presenter.rb | |
class ArticlePresenter < Presenter | |
delegate_name :article | |
def headline_heading | |
view.content_tag(:h1, article.headline, class: "article-headline") | |
end | |
end |
This file contains 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 ArticlesController < ApplicationController | |
view_accessor :article # https://gist.github.com/Odaeus/5238423 | |
def show | |
self.article = present(Article.find(params[:id]), ArticleDecorator) | |
end | |
end |
This file contains 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
# /app/presenters/presenter.rb | |
class Presenter < SimpleDelegator | |
include ERB::Util | |
def self.delegate_name(name) | |
alias_method name, :__getobj__ | |
end | |
def initialize(base_object, view_context) | |
super base_object | |
@view_context = view_context | |
end | |
def view | |
@view_context | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this.