Understanding Blocks in Ruby / Rails
I have used scaffolding to create a CRUD system for posts. In the controller, I see the following:
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 it
respond_to
and where does it come from? Since it uses an operatordo
, it is some kind of iterable list I guess. On eachformat
in this list, it will execute methodshtml
andjson
. -
How does it work
{ render json: @posts }
in relation to the methodjson
? Passingrender json: @posts
as a method argument? Whetherrender
andjson
subject to each object? I have never seen colon notation used outside of symbols.
source to share
- PostsController inherits methods from ApplicationController and ApplicationController inherits from ActionController :: Base . This is where it comes from
responds_to
. A topic worth paying attention to is "finding a method". -
do ... end
- one of the ways to record a block.{ render json: @posts }
is another way. -
json: "foo"
- a more modern alternative to writing:json => "foo"
-
format
is an arbitrary variable that you prepare for use within a block.render
is a method and a:json
is a symbol.respond_to
will respond to user requests that conform to the Rails format requirements. - And to understand the method there is also the following:
http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
And if you want to look at the source (it's a bit thick), for example, in the method respond_with
Paul was talking about, that's in the Rails source here:
rails / actionpack / Library / action_controller / metal / mime_responds.rb
source to share
First of all, respond_to
not modern stuff in Rails. But I will provide a link for an explanation anyway .
The more modern respond_with helper .
You might find this screencast useful.
source to share