Created
December 27, 2013 01:38
-
-
Save jay16/8141250 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Request資訊收集 | |
在Controller的Action之中,Rails提供了一些方法可以讓你得知此request各種資訊,包括: | |
action_name 目前的Action名稱 | |
cookies Cookie 下述 | |
headers HTTP標頭 | |
params 包含用戶所有傳進來的參數Hash,這是最常使用的資訊 | |
request 各種關於此request的詳細資訊 | |
request_method | |
method | |
delete?, get?, head?, post?, put? | |
xml_http_request? 或 xhr? | |
url | |
protocol, host, port, path 和 query_string | |
domain | |
host_with_port | |
port_string | |
ssl? | |
remote_ip? | |
path_without_extension, path_without_format_and_extension, format_and_extension, relative_path | |
env | |
accepts | |
format | |
mime_type | |
content_type | |
headers | |
body | |
content_length | |
response 代表要回傳的內容,會由Rails設定好。通常你會用到的時機是你想加特別的Response Header。 | |
session Session下述 | |
正確的說,params這個Hash是ActiveSupport::HashWithIndifferentAccess物件,而不是普通的Hash而已。Ruby內建的Hash,用Symbol的hash[:foo]和用字串的hash["foo"]是不一樣的,這在混用的時候常常搞錯而取不到值,算是常見的臭蟲來源。Rails在這裡使用的ActiveSupport::HashWithIndifferentAccess物件,無論鍵是Symbol或字串,都指涉相同的值,減少麻煩。 | |
做过JSP/.NET/PHP开发的朋友对request、response、session、cookie概念比较熟悉,但在Rails开发时很少接触这些概念,这是因为Rails把这些东西做了很好的封装,以至于我们几乎不需要专门与它们打交道。如果你想看到封闭后的东西,Rails中有个gem叫Rack,可以了解一下。下面介绍一些访问这些变量的简便方法 | |
在Controller的每个action中你都可以使用下面变量: | |
action_name:当前action的名字 | |
cookies:查看和设置浏览器cookie | |
headers:response将要使用的HTTP头信息组成的一个hash,一般设置Content-Type时才用 | |
params:这个很常用,请求参数组成的一个hash,params[:id]与params['id']相等。 | |
request:收到的请求,包含以下属性: | |
request_method:返回请求方法,有:delete,:get,:head,:post,:put | |
method:与request_method相同,除了:head会返回:get。因为这两个从程序角度来看功能是一样的。 | |
delete?,get?,head?,post?,put?:判断请求方法返回true或false | |
xml_http_request?和xhr?:ajax请求返回true,否则返回false。注意它和method参数是无关的。 | |
url:返回request的完整URL | |
remote_ip:返回远程IP地址。如果客户端使用proxy可能返回多于一个地址。 | |
headers:请求的http headers | |
body:请求的body构成的I/O流 | |
response:响应对象 | |
session:session组成的hash | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment