Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active April 19, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hopsoft/6519388 to your computer and use it in GitHub Desktop.
Save hopsoft/6519388 to your computer and use it in GitHub Desktop.
Rails presenter base class.
# app/presenters/presenter.rb
require "delegate"
class Presenter < SimpleDelegator
attr_reader :model, :controller
def initialize(model, controller)
@controller = controller
super(@model = model)
end
end
# app/presenters/user_presenter.rb
class UserPresenter < Presenter
def render_errors
# logic here ...
controller.render_to_string(
:partial => "/path/to/partial",
:locals => { :model => self }
)
end
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = UserPresenter.new(User.new, self)
end
def create
user = User.new(user_params)
if user.save
redirect_to show_user_path(user)
else
@user = UserPresenter.new(user, self)
render "new"
end
end
end
<!-- app/views/users/new.html.erb -->
<%= @user.render_errors %>
<%= form_for @user ... do |f| %>
...
<% end %>
@billychan
Copy link

The pattern is simple and nice!

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