Skip to content

Instantly share code, notes, and snippets.

@Odaeus
Last active October 11, 2019 23:55
Show Gist options
  • Save Odaeus/92a9f78df479ffa9bd09 to your computer and use it in GitHub Desktop.
Save Odaeus/92a9f78df479ffa9bd09 to your computer and use it in GitHub Desktop.
Simple Presenter Pattern
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
# /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
class ArticlesController < ApplicationController
view_accessor :article # https://gist.github.com/Odaeus/5238423
def show
self.article = present(Article.find(params[:id]), ArticleDecorator)
end
end
# /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
@andreimoment
Copy link

Thank you for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment