OSDN Git Service

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