Dry-out your controllers with some responders
Responders
View Slide
©2015 Infinum student academyPostsController#create@post = Post.new(post_params)if @post.save(post_params)redirect_to @postflash[:notice] = 'Post was successfully updated.'elserender :newend
©2015 Infinum student academyWhat about internationalization?
©2015 Infinum student academyPostsController#create@post = Post.new(post_params)if @post.saveflash[:notice] = I18n.t(‘flash.posts.create.notice’)redirect_to @postelserender :newend
©2015 Infinum student academyThe update action is very similar
©2015 Infinum student academyPostsController#update@post = Post.find(params[:id])if @post.update(post_params)flash[:notice] = I18n.t(‘flash.posts.update.notice’)redirect_to @postelserender :editend
©2015 Infinum student academyThe restful controller pseudocode:initialize_resourcecan it be saved?flashredirectelserenderend
Meet the responders..
©2015 Infinum student academyConvenient wrappers for RESTcontrollers@post = Post.create(post_params)respond_with @post
©2015 Infinum student academyKnows what translation to look at
©2015 Infinum student academyUniversal translation for all controllersflash:actions:create:notice: "%{resource_name} was successfully created."update:notice: "%{resource_name} was successfully updated."destroy:notice: "%{resource_name} was successfully destroyed."alert: "%{resource_name} could not be destroyed."
©2015 Infinum student academyTranslation per controllerflash:posts:create:notice: "Your post was created and will be published soon"
©2015 Infinum student academyNeed a non-standard redirectlocation?@post = Post.create(post_params)respond_with @post, location: -> { posts_path }
©2015 Infinum student academyNeed a non-standard renderingtemplate?@post = Post.create(post_params)respond_with @post, action: ‘shared/posts/new’
History
©2015 Infinum student academyResponders• Extracted from Rails 4.2 to a separate gem• Maintained by Plataformatec• authors of Devise & Simple Form
©2015 Infinum student academyWhy were they extracted from Rails?
©2015 Infinum student academyrespond_to do |format|format.xml { render xml: @model }format.json { render json: @model }endis clearer than…respond_with @model
©2015 Infinum student academyI only use them for Html API’s
Fin.