telkins
telkins

Reputation: 10550

Understanding blocks in Ruby/Rails

I used scaffolding to create a CRUD system for posts. In the controller, I see this:

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

Upvotes: 3

Views: 108

Answers (2)

eeeeeean
eeeeeean

Reputation: 1834

  1. PostsController inherits methods from ApplicationController and ApplicationController inherits from ActionController::Base. That's where responds_to comes from. The subject there worth looking into is "method lookup".
  2. do ... end is one way of writing a block. { render json: @posts } is another way.
  3. json: "foo" is a more modern alternative to writing :json => "foo"
  4. format is an arbitrary variable you're cooking up to use inside the block. render is a method and :json is a symbol. respond_to will respond to user requests that Rails format responses accordingly.
  5. And for understanding the method, there's also this:

http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

And if you want to look at the source (it's a little thick), for example at the respond_with method that Paul mentioned, that's in the Rails source here:

rails/actionpack/lib/action_controller/metal/mime_responds.rb

Upvotes: 3

Paul Brit
Paul Brit

Reputation: 5941

First of all, respond_to isn't modern stuff in Rails. But I will provide reference to explanation anyway.

More modern helper is respond_with.

Probably, this screencast will be useful for you.

Upvotes: 1

Related Questions