Skip to content

Instantly share code, notes, and snippets.

@francois-blanchard
Last active April 27, 2016 14:38
Show Gist options
  • Save francois-blanchard/f0f1f1114f3a29dc5913b5d786d61076 to your computer and use it in GitHub Desktop.
Save francois-blanchard/f0f1f1114f3a29dc5913b5d786d61076 to your computer and use it in GitHub Desktop.
Presenters in Rails

Presenters in Rails

Without presenter

View

<h1>@post.title</h1>
<span>@post.publication_status</span>

Controller

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
  end
end

Model

class Post < ActiveRecord::Base
  def publication_status
    published_at || 'Draft'
  end
end

With presenter

View

<h1>@post.title</h1>
<span>@post.publication_status</span>

Controller

class PostsController < ApplicationController
  def show
    post = Post.find(params[:id])
    @post = PostPresenter.new(post)
  end
end

Models

class Post < ActiveRecord::Base
end
class PostPresenter
  def initialze(post)
    @post = post
  end
  def publication_status
    @post.published_at || 'Draft'
  end
end

With helper presenter

View

<% present(@post) do |post| %>
  <h1>post.title</h1>
  <span>post.publication_status</span>
<% end %>

Controller

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
  end
end

Models

class Post < ActiveRecord::Base
end
class PostPresenter
  def initialze(post)
    @post = post
  end
  def publication_status
    @post.published_at || 'Draft'
  end
end

Helper

module ApplicationHelper
  def present(model)
    klass = "#{model.class}Presenter".constantize
    presenter = klass.new(model)
    yield(presenter) if block_given?
  end
end

Source : http://nithinbekal.com/posts/rails-presenters/

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