Last active
April 19, 2019 14:28
-
-
Save hopsoft/6519388 to your computer and use it in GitHub Desktop.
Rails presenter base class.
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 | |
require "delegate" | |
class Presenter < SimpleDelegator | |
attr_reader :model, :controller | |
def initialize(model, controller) | |
@controller = controller | |
super(@model = model) | |
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/user_presenter.rb | |
class UserPresenter < Presenter | |
def render_errors | |
# logic here ... | |
controller.render_to_string( | |
:partial => "/path/to/partial", | |
:locals => { :model => self } | |
) | |
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/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 |
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/views/users/new.html.erb --> | |
<%= @user.render_errors %> | |
<%= form_for @user ... do |f| %> | |
... | |
<% end %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The pattern is simple and nice!