简体   繁体   中英

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
  • What is respond_to and where does it come from? Since it is using the do operator, it is some sort of iterable list, I'm assuming. On each format in that list, it will perform the html and json methods.

  • How does { render json: @posts } work in relation to the json method? Is render json: @posts being passed as an argument to the method? Is render and json each an object? I've never seen the colon notation used outside of symbols.

  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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM