# Metal 文件下的内容

Metal 是请求从路由到 Controller 的中转站。

**类方法：**

```
action

use
middleware & middleware_stack

controller_name
```

**实例方法：**

```
dispatch

content_type
content_type=

location
location=

params
params=

status
status=

performed?

response_body=

controller_name

env

url_for
```

`self.action` 和 `dispatch` 为转移到下一站场起到了很大的作用。

```ruby
# Action Dispatch 转发过来的请求，要先经过层层的 middleware 处理，才能到达指定的 action.
def self.action(name, klass = ActionDispatch::Request)
  if middleware_stack.any?
    middleware_stack.build(name) do |env|
      new.dispatch(name, klass.new(env))
    end
  else
    lambda { |env| new.dispatch(name, klass.new(env)) }
  end
end
```

从堆栈里取 middleware 并处理。

`use` 方法把 middleware 放入 middleware stack，也很重要。

```ruby
class PostsController < ApplicationController
  use AuthenticationMiddleware, except: [:index, :show]
end
```

除此之外，需要清楚：

```ruby
class_attribute :middleware_stack
self.middleware_stack = ActionController::MiddlewareStack.new
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kelby.gitbook.io/rails-beginner-s-guide/actioncontroller/metal/metal_file.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
