Understanding Ruby Syntax

Possible duplicates:
What is the best way to learn Ruby? Explain Iterator syntax in Ruby on Rails

I'm still studying ruby, ruby ​​on rails and the like. I’m getting a better understanding of all the syntaxes of rubies and rails, but I’m a bit puzzled.

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @contact_lists }
end

response_to is a method that takes care, I think. Both formats look like they might be method calls, but I don't know.

+3
source share
3 answers

respond_tois a method that takes a block. A block takes one argument, which is called here format.

format. html, . xml, .

. :xml @contact_lists.

+6

, .

Ruby- , , .

, :

respond_to do |format| 

respond_to , format, .

    format.html # index.html.erb

format html

    format.xml  { render :xml => @contact_lists }

xml, (do/en {}, - .)

end

. , .

+4

, .

, , reply_to documentation. , Rails 3.

- - :

def index
  @people = Person.find(:all)
end

. , -, :

def index
  @people = Person.find(:all)

  respond_to do |format|
    format.html
    format.xml { render :xml => @people.to_xml }
  end
end

, " HTML , , , XML, XML ". (Rails HTTP Accept , .)

Suppose you have an action that adds a new person, not necessarily creating their company (by name), if it doesn’t already exist, without web services, it might look like this:

def create
  @company = Company.find_or_create_by_name(params[:company][:name])
  @person  = @company.people.create(params[:person])

  redirect_to(person_list_url)
end

. The same actions, with web service support, baked in:

def create
  company  = params[:person].delete(:company)
  @company = Company.find_or_create_by_name(company[:name])
  @person  = @company.people.create(params[:person])

  respond_to do |format|
    format.html { redirect_to(person_list_url) }
    format.js
    format.xml  { render :xml => @person.to_xml(:include => @company) }
  end
end
+3
source

Source: https://habr.com/ru/post/1764773/


All Articles