OSDN Git Service

Regular updates
[twpd/master.git] / rails-controllers.md
1 ---
2 title: Controllers
3 category: Rails
4 ---
5
6 ### Common stuff
7
8     redirect_to root_url
9     redirect_to root_url, notice: "Good."
10
11 ### Special hashes
12
13     session[:user_id] = nil
14
15     flash[:notice] = "Hello"    # Gets flushed on next request
16     flash.keep                  # Persist flash values
17     flash.now[:error] = "Boo"   # Available on the same request
18
19     cookies[:hello] = "Hi"
20
21     params[:page]
22
23     # params is a combination of:
24     query_parameters
25     path_parameters
26     request_parameters
27
28 ### respond_to
29
30     respond_to do |format|
31       format.html
32       format.xml  { render xml: @users }
33       format.json { render json: @users }
34       format.js    # Will be executed by the browser
35     end
36
37 ### default_url_options
38
39     # The options parameter is the hash passed in to 'url_for'
40     def default_url_options(options)
41       {:locale => I18n.locale}
42     end
43
44 ### Filters
45
46     # Filter with callbacks
47     before_filter :authenticate
48     before_filter :authenticate, except: [:login]
49     before_filter :authenticate, only: [:login]
50     def authenticate
51       redirect_to login_url unless controller.logged_in?
52     end
53
54     # Filter with inline
55     before_filter do |controller|
56       redirect_to login_url unless controller.logged_in?
57     end
58
59     # Filter with external classes
60     before_filter LoginFilter
61     class LoginFilter
62       def self.filter(controller) ...; end
63     end
64
65     # Filter exceptions
66     skip_before_filter :require_login, only: [:new, :create]
67
68     # Before/after filters
69     around_filter :wrap_in_transaction
70     def wrap_in_transaction(&blk)
71       ActiveRecord::Base.transaction { yield }
72     end
73
74 ### HTTP basic authentication
75
76     before_filter :authenticate
77
78     # Basic authentication:
79     def authenticate
80       authenticate_or_request_with_http_basic { |u, p|
81         u == "root" && p == "alpine"
82       }
83     end
84
85     # ...or digest (hashed) authentication:
86     # uses the ha1 hash (username:realm:password)
87     def authenticate_by_digest
88       realm = "Secret3000"
89       users = {
90         "rsc" => Digest::MD5.hexdigest("rsc:#{realm}:passwordhere")
91       }
92
93       authenticate_or_request_with_http_digest(realm) { |user|
94         users[user]
95       }
96     end
97
98     # For integration tests
99     def test_access
100       auth = ActionController::HttpAuthentication::Basic.encode_credentials(user, pass)
101       get "/notes/1.xml", nil, 'HTTP_AUTHORIZATION' => auth
102     end
103
104     # Token auth
105     is_logged_in = authenticate_with_http_token do |token, options|
106       token == our_secret_token
107     end
108
109     request_http_token_authentication  unless is_logged_in
110
111 ### Request/response
112
113     request.host            #=> "www.example.com"
114     request.domain          #=> "www.example.com"
115     request.domain(n=2)     #=> "example.com"
116     request.port            #=> 80
117     request.protocol        #=> "http://"
118     request.query_string    #=> "q=duck+tales"
119     request.url             #=> "http://www.example.com/search?q=duck+tales"
120     request.fullpath        #=> "/search?q=duck+tales"
121
122     request.headers         # Returns a hash
123
124     request.format          #=> "text/html"
125     request.remote_ip       #=> "203.167.220.220"
126     request.local?          #=> true (if localhost/127.0.0.1)
127
128     request.xhr?
129
130     request.method          #=> "POST"
131     request.method_symbol   #=> :post
132     request.get?
133     request.post?
134     request.put?
135     request.delete?
136     request.head?
137
138 ### response
139
140     response.body
141     response.status         #=> 404
142     response.location       # Redirect location
143     response.content_type
144     response.charset
145     response.headers
146
147     response.headers["Content-Type"] = "application/pdf"
148
149 ### Streaming
150
151     send_data pdfdata, filename: "foo.pdf", type: "application/pdf"
152     send_file Rails.root.join('public','filename.txt') [filename: '..', type: '..']
153
154 ### References
155
156  * [Guide](http://guides.rubyonrails.org/action_controller_overview.html)
157  * [HttpAuthentication::Basic](http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html)
158  * [HttpAuthentication::Token](http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html)