-
Notifications
You must be signed in to change notification settings - Fork 3
Presenters: Typical Example
Zack Siri edited this page Dec 5, 2013
·
1 revision
This page will show you an example of what a typical rails app using presenter looks like.
contacts_controller.rb
class ContactsController < ApplicationController
respond_to :json, :html, :js
def index
@contacts = Contact.all
respond_with @contacts
end
def new
@contact = Contact.new
respond_with @contact
end
def create
@contact = Contact.new(contact_params)
if @contact.save
respond_with @contact
else
xms_error @contact
end
end
def edit
@contact = Contact.where(id: params[:id]).first
respond_with @contact
end
def update
@contact = Contact.where(id: params[:id]).first
if @contact.update_attributes(contact_params)
respond_with @contact
else
xms_error @contact
end
end
private
def contact_params
params.require(:contact).permit(:name, :email)
end
end
contacts_presenter.coffee
class Application.Presenters.ContactPresenter extends Transponder.Presenter
presenterName: 'contacts'
module: 'application'
index: ->
$(@element).html(@response)
edit: ->
$(@element).html(@response)
$(@element).modal()
new: ->
@edit()
create: ->
$(@element).append(@response)
$("#modal-box").modal('toggle')
update: ->
$(@element).replaceWith(@response)
$('#modal-box').modal('toggle')
error:
update: (errors, element) ->
for key, value of errors
$("input#contact_#{key}").tooltip
title: value[0]
$("input#contact_#{key}").tooltip('show')
create: (errors, element) ->
@update(errors, element)
You can see that code reuseability is great with Transponder's Presenters