Responders

5f81e2d2889d7642fd84c8b24db7ee17?s=47 DamirSvrtan
September 14, 2015

 Responders

Dry-out your controllers with some responders

5f81e2d2889d7642fd84c8b24db7ee17?s=128

DamirSvrtan

September 14, 2015
Tweet

Transcript

  1. Responders

  2. ©2015 Infinum student academy PostsController#create @post = Post.new(post_params) if @post.save(post_params)

    redirect_to @post flash[:notice] = 'Post was successfully updated.' else render :new end
  3. ©2015 Infinum student academy What about internationalization?

  4. ©2015 Infinum student academy PostsController#create @post = Post.new(post_params) if @post.save

    flash[:notice] = I18n.t(‘flash.posts.create.notice’) redirect_to @post else render :new end
  5. ©2015 Infinum student academy The update action is very similar

  6. ©2015 Infinum student academy PostsController#update @post = Post.find(params[:id]) if @post.update(post_params)

    flash[:notice] = I18n.t(‘flash.posts.update.notice’) redirect_to @post else render :edit end
  7. ©2015 Infinum student academy The restful controller pseudocode: initialize_resource can

    it be saved? flash redirect else render end
  8. Meet the responders..

  9. ©2015 Infinum student academy Convenient wrappers for REST controllers @post

    = Post.create(post_params) respond_with @post
  10. ©2015 Infinum student academy Knows what translation to look at

  11. ©2015 Infinum student academy Universal translation for all controllers flash:

    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."
  12. ©2015 Infinum student academy Translation per controller flash: posts: create:

    notice: "Your post was created and will be published soon"
  13. ©2015 Infinum student academy Need a non-standard redirect location? @post

    = Post.create(post_params) respond_with @post, location: -> { posts_path }
  14. ©2015 Infinum student academy Need a non-standard rendering template? @post

    = Post.create(post_params) respond_with @post, action: ‘shared/posts/new’
  15. History

  16. ©2015 Infinum student academy Responders • Extracted from Rails 4.2

    to a separate gem • Maintained by Plataformatec • authors of Devise & Simple Form
  17. ©2015 Infinum student academy Why were they extracted from Rails?

  18. ©2015 Infinum student academy respond_to do |format| format.xml { render

    xml: @model } format.json { render json: @model } end is clearer than… respond_with @model
  19. ©2015 Infinum student academy I only use them for Html

    API’s
  20. Fin.