Spec-Zone.ru › Ruby on Rails 7.2

class ActionController::Base

Parent:
Metal

Action Controller Base

Action Controllers are the core of a web request in Rails. They are made up of one or more actions that are executed on request and then either it renders a template or redirects to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.

By default, only the ApplicationController in a Rails application inherits from ActionController::Base. All other controllers inherit from ApplicationController. This gives you one class to configure things such as request forgery protection and filtering of sensitive request parameters.

A sample controller could look like this:

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def create
    @post = Post.create params[:post]
    redirect_to posts_path
  end
end

Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action after executing code in the action. For example, the index action of the PostsController would render the template app/views/posts/index.html.erb by default after populating the @posts instance variable.

Unlike index, the create action will not render a template. After performing its main purpose (creating a new post), it initiates a redirect instead. This redirect works by returning an external 302 Moved HTTP response that takes the user to the index action.

These two methods represent the two basic action archetypes used in Action Controllers: Get-and-show and do-and-redirect. Most actions are variations on these themes.

Requests

For every request, the router determines the value of the controller and action keys. These determine which controller and action are called. The remaining request parameters, the session (if one is available), and the full request with all the HTTP headers are made available to the action through accessor methods. Then the action is performed.

The full request object is available via the request accessor and is primarily used to query for HTTP headers:

def server_ip
  location = request.env["REMOTE_ADDR"]
  render plain: "This server hosted at #{location}"
end

Parameters

All request parameters, whether they come from a query string in the URL or form data submitted through a POST request are available through the params method which returns a hash. For example, an action that was performed through /posts?category=All&limit=5 will include { "category" => "All", "limit" => "5" } in params.

It’s also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:

<input type="text" name="post[name]" value="david">
<input type="text" name="post[address]" value="hyacintvej">

A request coming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" } }. If the address input had been named post[address][street], the params would have included { "post" => { "address" => { "street" => "hyacintvej" } } }. There’s no limit to the depth of the nesting.

Сессии

Сессии позволяют хранить объекты между запросами. Это полезно для объектов, которые ещё не готовы к сохранению, например, объект Signup, созданный в многостраничном процессе, или объекты, которые не сильно изменяются и постоянно нужны, например, объект User для системы, требующей входа. Однако сессии не следует использовать в качестве кэша для объектов, которые могут быть изменены неосознанно. Обычно слишком много усилий уходит на синхронизацию — базы данных справляются с этим лучше.

Вы можете поместить объекты в сессию, используя метод session, который обращается к хэшу:

session[:person] = Person.authenticate(user_name, password)

Вы можете получить его снова через тот же хэш:

"Hello #{session[:person]}"

Для удаления объектов из сессии можно либо присвоить отдельный ключ nil:

# removes :person from session
session[:person] = nil

или удалить всю сессию с помощью reset_session.

По умолчанию сессии хранятся в зашифрованном cookie браузера (см. ActionDispatch::Session::CookieStore). Таким образом, пользователь не сможет прочитать или изменить данные сессии. Однако пользователь может сохранить копию cookie даже после истечения срока его действия, поэтому следует избегать хранения конфиденциальной информации в сессиях на основе cookie.

Ответы

Каждый action приводит к ответу, который содержит заголовки и документ, которые будут отправлены браузеру пользователя. Фактический объект ответа генерируется автоматически с помощью render и redirect и не требует вмешательства пользователя.

Render

Action Controller отправляет содержимое пользователю, используя один из пяти методов рендеринга. Наиболее универсальный и распространенный — рендеринг шаблона. В Action Pack включен Action View, который позволяет рендерить ERB шаблоны. Он автоматически настроен. Контроллер передает объекты в представление, присваивая переменные экземпляра:

def show
  @post = Post.find(params[:id])
end

которые затем автоматически доступны представлению:

Title: <%= @post.title %>

Вы не обязаны полагаться на автоматический рендеринг. Например, действия, которые могут привести к рендерингу различных шаблонов, будут использовать ручные методы рендеринга:

def search
  @results = Search.find(params[:query])
  case @results.count
    when 0 then render action: "no_results"
    when 1 then render action: "show"
    when 2..10 then render action: "show_many"
  end
end

Подробнее о написании ERB и шаблонов Builder см. в ActionView::Base.

Перенаправления

Перенаправления используются для перемещения из одного action в другой. Например, после action create, который сохраняет запись в блоге в базу данных, мы можем захотеть показать пользователю новую запись. Так как мы следуем хорошим принципам DRY (Don’t Repeat Yourself), мы будем повторно использовать (и перенаправлять на) action show, который, мы предположим, уже создан. Код может выглядеть так:

def create
  @entry = Entry.new(params[:entry])
  if @entry.save
    # The entry was saved correctly, redirect to show
    redirect_to action: 'show', id: @entry.id
  else
    # things didn't go so well, do something else
  end
end

В этом случае после сохранения новой записи в базу данных пользователь перенаправляется на метод show, который затем выполняется. Обратите внимание, что это перенаправление на уровне HTTP, которое заставит браузер выполнить второй запрос (GET к action show), а не внутреннее перенаправление, которое вызовет как «create», так и «show» в одном запросе.

Узнайте больше о redirect_to и имеющихся у вас вариантах в ActionController::Redirecting.

Вызов нескольких перенаправлений или рендерингов

Action может выполнить только одно render или одно redirect. Попытка выполнить это снова приведет к ошибке DoubleRenderError:

def do_something
  redirect_to action: "elsewhere"
  render action: "overthere" # raises DoubleRenderError
end

Если вам нужно перенаправить при определенном условии, убедитесь, что добавили «return» для остановки выполнения.

def do_something
  if monkeys.nil?
    redirect_to(action: "elsewhere")
    return
  end
  render action: "overthere" # won't be called if monkeys is nil
end

Константы

MODULES
PROTECTED_IVARS

Определяют некоторые внутренние переменные, которые не должны передаваться в представление.

Публичные методы класса

without_modules(*modules) Show source
# File actionpack/lib/action_controller/base.rb, line 222
def self.without_modules(*modules)
  modules = modules.map do |m|
    m.is_a?(Symbol) ? ActionController.const_get(m) : m
  end

  MODULES - modules
end

Утилита, которая возвращает все модули, включенные в ActionController::Base, за исключением переданных в качестве аргументов:

class MyBaseController < ActionController::Metal
  ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left|
    include left
  end
end

Это обеспечивает больший контроль над тем, что вы хотите исключить, и упрощает создание базового класса контроллера вместо ручного перечисления требуемых модулей.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API