forked from otobrglez/webruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter5.html
660 lines (540 loc) · 33.6 KB
/
chapter5.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
<!doctype html>
<html>
<head>
<title>Programming for the Web with Ruby</title>
<meta charset="utf-8">
<meta name="author" content="Satish Talim" >
<meta name="keywords" content="programming, Ruby, Rack, Sinatra" >
<meta name="description" content="A Ruby programming tutorial on topics that hopefully will help those that have some knowledge of Ruby programming to get started with web programming." >
<link rel="stylesheet" href="stylesheets/intruby.css">
</head>
<body>
<div>
<p>
<strong>
<a href="chapter4.html"><Chapter 4 | </a>
<a href="toc.html">TOC | </a>
<a href="chapter6.html">Chapter 6></a>
</strong>
</p>
<h1 class="title">Day 5 and 6 - Spend more time here!</h1>
<h1>Learning Rack</h1>
<h2>Revisiting Ruby's proc object</h2>
<p>Note that I have Ruby 1.9.3 installed on a Windows box and all the programs in this article have been tested using that.</p>
<p>Remember the <a href="http://rubylearning.com/satishtalim/ruby_procs.html">proc object from Ruby</a>? <em>Blocks are not objects</em>, but they can be converted into objects of class <code>Proc</code>. This can be done by calling the <code>lambda</code> method of the class <code>Object</code>. A block created with <code>lambda</code> acts like a Ruby method. The class <code>Proc</code> has a method <code>call</code> that invokes the block.</p>
<p>Open a command window and type:</p>
<pre>$ irb --simple-prompt
>> my_proc = lambda {puts 'Proc Called'}
=> #<Proc:0x1fc9038@(irb):2(lambda)>
>> # method call invokes the block
?> my_proc.call
Proc Called
=> nil
>> exit
$
</pre>
<p>Close the command window.</p>
<h3>my_proc1.rb</h3>
<p>The above can be written in a Ruby program <b><code>my_proc1.rb</code></b>:</p>
<pre># my_proc1.rb
my_proc = lambda {puts 'Proc Called'}
my_proc.call
</pre>
<p>Open a command window and execute the <code>my_proc1.rb</code> program:</p>
<pre>$ ruby my_proc1.rb #=> Proc Called
</pre>
<p>Close the command window.</p>
<h2>Rack Documentation</h2>
<p><a href="http://rack.rubyforge.org/doc/">http://rack.rubyforge.org/doc/</a></p>
<h2>Rack Source Code</h2>
<p><a href="https://github.com/rack/rack">https://github.com/rack/rack</a></p>
<h2>Why Rack is important</h2>
<p>Rubyist <a href="http://merbist.com/">Matt Aimonetti</a> has this to say to all the participants of this course:</p>
<blockquote><p>Rack is the foundation of a great majority of modern Ruby web frameworks. This common interface between web servers and web applications is critical to understand since as a Ruby web developer you will more than likely have to deal with Rack middleware and/or Rack applications.</p>
<p>Rails for instance is built on top of Rack and it allows you to add or remove middleware as well as mount full Rack applications within your Rails app. Sinatra on the other hand is basically a library of helpers for Rack, making the development of Rack applications easier and more consistent while still being very flexible.</p>
<p>The good news is that the power of Rack is in its simplicity and therefore even someone who just started with Ruby should be able to quickly grasp its core concepts.</p></blockquote>
<h2>Rack Specification</h2>
<p>In the words of the author of Rack - <b>Christian Neukirchen</b>: <span style="background-color: #FFFFCC;">Rack aims to provide a minimal API for connecting web servers supporting Ruby (like WEBrick, Mongrel etc.) and Ruby web frameworks (like Rails, Sinatra etc.)</span>.</p>
<p>Web frameworks such as Sinatra are built on top of Rack or have a Rack interface for allowing web application servers to connect to them.</p>
<p>The premise of Rack is simple - it just allows you to easily deal with HTTP requests.</p>
<p>HTTP is a simple protocol: it basically describes the activity of a client sending a HTTP request to a server and the server returning a HTTP response. Both HTTP request and HTTP response in turn have very similar structures. A HTTP request is a triplet consisting of a method and resource pair, a set of headers and an optional body while a HTTP response is in triplet consisting of a response code, a set of headers and an optional body.</p>
<p>Rack maps closely to this. <span style="background-color: #FFFFCC;">A Rack application is a Ruby object (not a class) that responds to <code>call</code> and takes exactly one argument, the <em>environment</em>. The <em>environment</em> must be a true instance of <code>Hash</code>. This hash contains all the relevant information about the request: this includes the HTTP verb used by the request, the path that is requested, the headers that have been sent by the client, and so on. The app should return an <code>Array</code> of exactly three values: the <em>status</em> code (it must be greater than or equal to 100), the <em>headers</em> (must be a hash), and the <em>body</em> (the body commonly is an Array of Strings, the application instance itself, or a File-like object. The <em>body</em> (corresponding to a HTTP response) must respond to method <code>each</code> and must only yield <code>String</code> values.)</span></p>
<p>That's the Rack specification in a nutshell. You can check out the full details <a href="http://rack.rubyforge.org/doc/files/SPEC.html">here</a>. <b>Strictly speaking, you don't need the rack gem in order to write Rack ready applications</b>. Just stick to the specification and that's it.</p>
<h3>A Rack App without using the Rack gem</h3>
<h4>A simple Rack app - my_rack_proc</h4>
<p>Let us create our new <code>proc</code> object. Open a command window and type:</p>
<pre>$ irb --simple-prompt
>> my_rack_proc = lambda { |env| [200, {}, ["Hello. The time is #{Time.now}"]] }
=> #<Proc:0x1f4c358@(irb):5(lambda)>
>>
</pre>
<p>Now we can call the proc object <code>my_rack_proc</code> with the <code>call</code> method. In the above window type:</p>
<pre>>> my_rack_proc.call({})
=> [200, {}, ["Hello. The time is 2011-10-24 09:18:56 +0530"]]
>>
</pre>
<p><code>my_rack_proc</code> is our single line Rack application.</p>
<p>In the above example, we have used an empty hash for headers. Instead, let's have something in the header as follows:</p>
<pre>>> my_rack_proc = lambda { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
=> #<Proc:0x1f4c358@(irb):5(lambda)>
>>
</pre>
<p>Now we can call the proc object <code>my_rack_proc</code> with the <code>call</code> method. In the above window type:</p>
<pre>>> my_rack_proc.call({})
=> [200, {"Content-Type" => "text/plain"}, ["Hello. The time is 2011-10-24 09:18:56 +0530"]]
>> exit
$
</pre>
<p>Close the command window.</p>
<h4>my_rack_proc.rb</h4>
<p>What we saw above can be written in a Ruby program <b><code>my_rack_proc.rb</code></b>:</p>
<pre># my_rack_proc.rb
my_rack_proc = lambda { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
puts my_rack_proc.call({})
</pre>
<p>Open a command window and execute the <code>my_rack_proc.rb</code> program:</p>
<pre>$ ruby my_rack_proc.rb
200
{"Content-Type"=>"text/plain"}
Hello. The time is 2011-12-07 09:42:31 +0530
</pre>
<p>Close the command window.</p>
<h4>A Simple Rack Exercise</h4>
<p>Write a simple Rack application which when run, accepts a command-line argument. Display this command-line argument. An example:</p>
<pre>$ ruby simple_rack.rb "Hello World"
200
{"Content-Type"=>"text/plain"}
Command line argument you typed was: Hello World
$
</pre>
<h2>Installing Rack gem</h2>
<p>Rack gem is a <a href="http://rack.rubyforge.org/doc/classes/Rack.html">collection of utilities and facilitating classes</a>, to make life easier for anyone developing Rack applications. It includes basic implementations of request, response, cookies, sessions and a good number of useful middlewares.</p>
<p>Rack includes <em>handlers</em> that connect Rack to all these web application servers (WEBrick, Mongrel etc.).</p>
<p>Rack includes <em>adapters</em> that connect Rack to various web frameworks (Sinatra, Rails etc.).</p>
<p>Between the server and the framework, Rack can be customized to your applications needs using <em>middleware</em>. <span style="background-color: #FFFFCC;">The fundamental idea behind Rack middleware is - come between the calling client and the server, process the HTTP request before sending it to the server, and processing the HTTP response before returning it to the client</span>.</p>
</div>
<div style="width:image 560 px; font-size:80%; text-align:center;"><img src="images/rack.jpg" alt="Rack App" style="padding-bottom:0.5em;" /><br />A Rack App</div>
<div>
<p>Let's check if we already have rack with us. Open a command window and type:</p>
<pre>$ irb --simple-prompt
>> require 'rack'
=> true
>>
</pre>
<p>Yes, rack's already there on your machine. If rack's not there you will get an error like:
<pre>LoadError: no such file to load -- rack
</pre>
<p>In case you do not have rack, install it by typing:</p>
<pre>$ gem install rack
</pre>
<p>We can run our previously written Rack application (<code>my_rack_proc</code>) with any of the Rack handlers.</p>
<p>To look at the Rack handlers available, in the already open irb window type:</p>
<pre>>> require 'rack'
=> true
>> Rack::Handler.constants
=> [:CGI, :FastCGI, :Mongrel, :EventedMongrel, :SwiftipliedMongrel, :WEBrick, :LSWS, :SCGI, :Thin]
>>
</pre>
<p>To get a handler for say <code>WEBrick</code> (the default <code>WEBrick</code>, web application server, that comes along with Ruby), type:</p>
<pre>>> Rack::Handler::WEBrick
=> Rack::Handler::WEBrick
>>
</pre>
<p>All of these handlers have a common method called <code>run</code> to run all the Rack based applications.</p>
<pre>>> my_rack_proc = lambda { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
>> Rack::Handler::WEBrick.run my_rack_proc
[2011-10-24 10:00:45] INFO WEBrick 1.3.1
[2011-10-24 10:00:45] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-24 10:00:45] INFO WEBrick::HTTPServer#start: pid=1788 port=80
</pre>
<p>Open a browser window and type the url: <a href="http://localhost/">http://localhost/</a></p>
<p>In your browser window, you should see a string, something like this:</p>
<pre>Hello. The time is 2011-10-24 10:02:20 +0530
</pre>
<p><b>Note</b>: If you already have something running at port 80, you could have run this app at a different port, say 9876:</p>
<pre>>> Rack::Handler::WEBrick.run my_rack_proc, :Port => 9876
[2011-10-24 11:32:21] INFO WEBrick 1.3.1
[2011-10-24 11:32:21] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-24 11:32:21] INFO WEBrick::HTTPServer#start: pid=480 port=9876
</pre>
<p>In the browser window you would have typed the url: <a href="http://localhost:9876/">http://localhost:9876/</a></p>
<p>In the command window, press <b>Ctrl C</b> to stop the <b>WEBrick</b> server. Close the command window.</p>
<p><b>Note</b>: This may cause the <b>WEBrick</b> server not to stop in some distributions, showing the following error in the console:</p>
<pre>ERROR Interrupt:
/usr/local/rvm/rubies/ruby-1.9.3-head/lib/ruby/1.9.1/webrick/server.rb:98:in `select'
</pre>
<p>In order to stop WEBrick, press <b>Ctrl z</b> to send the process to background and then kill it using <i>kill -9 %1</i> (run the <i>jobs</i> command to ensure that 1 is the right number of your job).</p>
<p>You may want to use <b>Thin</b> handler instead of <b>WEBrick</b>.</p>
<h3>my_rack_proc2.rb</h3>
<p>What we saw above can be written in a Ruby program <b><code>my_rack_proc2.rb</code></b>:</p>
<pre># my_rack_proc2.rb
require 'rack'
my_rack_proc = lambda { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
Rack::Handler::WEBrick.run my_rack_proc, :Port => 9876
</pre>
<p>Open a command window and execute the <code>my_rack_proc2.rb</code> program:</p>
<pre>$ ruby my_rack_proc2.rb
[2011-12-07 09:54:48] INFO WEBrick 1.3.1
[2011-12-07 09:54:48] INFO ruby 1.9.3 (2011-10-30) [i386-mingw32]
[2011-12-07 09:54:48] INFO WEBrick::HTTPServer#start: pid=5992 port=9876
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9876/">http://localhost:9876/</a></p>
<p>In your browser window, you should see a string, something like this:</p>
<pre>Hello. The time is 2011-12-07 09:55:52 +0530
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h3>Another Rack app - my_method</h3>
<p>A Rack app need not be a lambda; it could be a method. Open a command window and type:</p>
<pre>$ irb --simple-prompt
>> require 'rack'
=> true
>> def my_method(env)
>> [200, {}, ["method called"]]
>> end
=> nil
</pre>
<p>We declare a method <code>my_method</code> that takes an argument <code>env</code>. The method returns three values.</p>
<p>In the open irb shell, type:</p>
<pre>>> Rack::Handler::WEBrick.run method(:my_method)
[2011-10-24 14:32:05] INFO WEBrick 1.3.1
[2011-10-24 14:32:05] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-24 14:32:05] INFO WEBrick::HTTPServer#start: pid=1644 port=80
</pre>
<p>Open a browser window and type the url: <a href="http://localhost/">http://localhost/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>method called
</pre>
<p><code>Method</code> objects are created by <code>Object#method</code>. They are associated with a particular object (not just with a class). They may be used to invoke the method within the object. The <code>Method.call</code> method invokes the method with the specified arguments, returning the method's return value.</p>
<p>Press <b>Ctrl-C</b> in irb to stop the <b>WEBrick</b> server. Close the command window.</p>
<h4>my_rack2.rb</h4>
<p>What we saw above can be written in a Ruby program <b><code>my_rack2.rb</code></b>:</p>
<pre># my_rack2.rb
require 'rack'
def my_method env
[200, {}, ["method called"]]
end
Rack::Handler::WEBrick.run method(:my_method)
</pre>
<p>Open a command window and execute the <code>my_rack2.rb</code> program:</p>
<pre>$ ruby my_rack2.rb
[2011-12-07 10:11:48] INFO WEBrick 1.3.1
[2011-12-07 10:11:48] INFO ruby 1.9.3 (2011-10-30) [i386-mingw32]
[2011-12-07 10:11:48] INFO WEBrick::HTTPServer#start: pid=6664 port=80
</pre>
<p>Open a browser window and type the url: <a href="http://localhost/">http://localhost/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>method called
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h3>A Simple Rack Exercise with rack gem</h3>
<p>Previously you have written a simple Rack application which when run, accepts a command-line argument. Display this command-line argument. An example:</p>
<pre>$ ruby simple_rack.rb "Hello World"
200
{"Content-Type"=>"text/plain"}
Command line argument you typed was: Hello World
$
</pre>
<p>Re-write this app using the rack gem. Also, the server should be running on port 8500.</p>
<h2>Using rackup</h2>
<p>The rack gem comes with a bunch of useful stuff to make life easier for a rack application developer. <code>rackup</code> is one of them.</p>
<p><code>rackup</code> is a useful tool for running Rack applications. <code>rackup</code> automatically figures out the environment it is run in, and runs your application as FastCGI, CGI, or standalone with Mongrel or WEBrick - all from the same configuration.</p>
<p>To use <code>rackup</code>, you'll need to supply it with a rackup config file. By convention, you should use <code>.ru</code> extension for a rackup config file. Supply it a run Rack Object and you're ready to go:</p>
<pre>$ rackup config.ru
</pre>
<p>By default, <code>rackup</code> will start a server on port 9292.</p>
<p>To view <code>rackup</code> help, open a command window and type:</p>
<pre>$ rackup --help
</pre>
<p>Let us create a <code>config.ru</code> file that contains the following:</p>
<pre>run lambda { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
</pre>
<p>This file contains <code>run</code>, which can be called on anything that responds to a <code>.call</code>. Also note that you don't need to <code>require 'rack'</code> since you use <code>rackup</code> which already loads rack.</p>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, type:</p>
<pre>$ rackup config.ru
[2011-10-24 15:18:03] INFO WEBrick 1.3.1
[2011-10-24 15:18:03] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-24 15:18:03] INFO WEBrick::HTTPServer#start: pid=3304 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello. The time is 2011-10-24 15:18:10 +0530
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h4>my_app.rb</h4>
<p>Now let's move our application from the <code>config.ru</code> file to <b><code>my_app.rb</code></b> file as follows:</p>
<pre># my_app.rb
class MyApp
def call(env)
[200, {"Content-Type" => "text/html"}, ["Hello Rack Participants from across the globe"]]
end
end
</pre>
<p>Also, our <code>config.ru</code> will change to:</p>
<pre>require './my_app'
run MyApp.new
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, open a command window and type:</p>
<pre>$ rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello Rack Participants from across the globe
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h3>Exercise: A Simple Rack app with rackup</h3>
<p>Previously you have written a simple Rack application which when run, accepts a command-line argument. Display this command-line argument. An example:</p>
<pre>$ ruby simple_rack.rb "Hello World"
200
{"Content-Type"=>"text/plain"}
Command line argument you typed was: Hello World
$
</pre>
<p>Re-write this app using rackup and config.ru.</p>
<h3>Using Rack::Request and Rack::Response</h3>
<p>We will use <code>cURL</code>, <code>Rack::Request</code> and <code>Rack::Response</code> in the code examples that follow.</p>
<p>First, let's look at the following <code>cURL</code> command:</p>
<pre>curl -X request
</pre>
<p>(HTTP) Specifies a custom request (GET, POST) to use when communicating with the HTTP server. The specified request will be used instead of the standard GET.</p>
<pre>curl -X POST -d data
</pre>
<p>(HTTP) Sends the specified data in a POST request to the HTTP server, in a way that can emulate as if a user has filled in a HTML form and pressed the submit button. Note that the data is sent exactly as specified with no extra processing (with all newlines cut off). The data is expected to be "url-encoded". This will cause <code>cURL</code> to pass the data to the server using the content-type application/x-www-form-urlencoded. If more than one -d/--data option is used on the same command line, the data pieces specified will be merged together with a separating &-letter. Thus, using '-d name=daniel -d skill=lousy' would generate a post chunk that looks like 'name=daniel&skill=lousy'.</p>
<p>If you start the data with the letter @, the rest should be a file name to read the data from, or - if you want <code>cURL</code> to read the data from stdin. The contents of the file must already be url-encoded.</p>
<p>Do check out the source code for <a href="https://github.com/rack/rack/blob/master/lib/rack/request.rb">Rack::Request</a> and <a href="https://github.com/rack/rack/blob/master/lib/rack/response.rb">Rack::Response</a>. Let us write a program to explore these two:</p>
<p>Our <code>config.ru</code> will be:</p>
<pre>require './my_request'
run MyRequest.new
</pre>
<p>Our application <b><code>my_request.rb</code></b> is as follows:</p>
<pre># my_request.rb
class MyRequest
def call(env)
req = Rack::Request.new(env)
name = req.params['name']
text = req.params['text']
Rack::Response.new.finish do |res|
res['Content-Type'] = 'text/plain'
res.status = 200
str = "Parameters sent: name - #{name} | text - #{text}"
res.write str
end
end
end
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, open a command window and type:</p>
<pre>$ rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Our client is <code>cURL</code>. Open a Bash shell and type:</p>
<pre>$ curl -X POST -d 'name=Satish Talim&text=This course is awesome!' localhost:9292
</pre>
<p>In your Bash shell, you should see something like this:</p>
<pre>Parameters sent: name - Satish Talim | text - This course is awesome!
</pre>
<p>Type <code>exit</code> in your Bash shell and press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h3>A very basic practical Rack app</h3>
<p><b>Credit:</b> <a href="https://github.com/mattetti">Matt Aimonetti</a></p>
<p>Matt has been kind enough to <a href="https://gist.github.com/1447058">write this app</a> for us. It's a very basic rack application showing how to use a router based on the uri and how to process requests based on the HTTP method used. The explanation is <a href="https://github.com/rack/rack/wiki/Rack-app-with-uri-and-HTTP-specific-responses">here</a>.</p>
<h3>Another practical Rack app</h3>
<p><b>Credit:</b> <a href="https://github.com/rkh">Konstantin Haase</a></p>
<p>Konstantin has provided us with <a href="https://gist.github.com/57c8449e305a55a80e21">another practical Rack app</a>, where we use <code>cURL</code> to upload a text file and which then gets sorted.</p>
<h3>Exercise: An app using Rack::Request and Rack::Response</h3>
<p>Write a rack app that uses <code>Rack::Request</code> and <code>Rack::Response</code> to reverse a string passed to the app by a client. Post your code in the technical forum.</p>
<h4>Rack middleware</h4>
<p><b>Credit:</b> <a href="https://github.com/mattetti">Matt Aimonetti</a></p>
<p><b>Remember</b>: <span style="background-color: #FFFFCC;">The fundamental idea behind Rack middleware is - come between the calling client and the server, process the HTTP request before sending it to the server, and processing the HTTP response before returning it to the client</span>.</p>
<p>Write the following program <code>my_middleware.rb</code>:</p>
<pre># my_middleware.rb
module MyMiddleware
class Hello
def initialize(app)
@app = app
end
def call(env)
if env['PATH_INFO'] == '/hello'
[200, {"Content-Type" => "text/plain"}, ["Hello from the middleware!"]]
else
# forward the request
@app.call(env)
end
end
end
end
</pre>
<p>In the above program, we are using a <a href="http://rubylearning.com/satishtalim/modules_mixins.html">module</a>. Also, we keep the application reference in the <code>@app</code> variable when a new instance of the middleware is created.</p>
<p><em><code>my_middleware.rb</code> is a rack middleware living on its own, that you need to require it in your app and then call it by telling rack to use it</em>.</p>
<p>Create our app <code>config.ru</code> as follows:</p>
<pre>require './my_middleware'
use MyMiddleware::Hello # this comes in between
run Proc.new{|env| [200, {"Content-Type" => "text/plain"}, ['Try accessing visiting /hello']] }
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, open a command window and type:</p>
<pre>rackup config.ru
[2011-12-11 09:33:40] INFO WEBrick 1.3.1
[2011-12-11 09:33:40] INFO ruby 1.9.3 (2011-10-30) [i386-mingw32]
[2011-12-11 09:33:40] INFO WEBrick::HTTPServer#start: pid=3532 port=9292
</pre>
<p><b>Note</b>: Under the hood, <code>rackup</code> converts your <code>config.ru</code> script to an instance of <a href="http://rack.rubyforge.org/doc/classes/Rack/Builder.html">Rack::Builder</a> (which we shall talk about soon). <code>Rack::Builder#use</code> adds a middleware to the rack application stack created by <code>Rack::Builder</code>.</p>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Try accessing visiting /hello
</pre>
<p>That's the normal response from your app.</p>
<p>Next, in your browser window type the url: <a href="http://localhost:9292/hello">http://localhost:9292/hello</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello from the middleware!
</pre>
<p>That's your middleware talking!</p>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h3>An Exercise on Rack middleware</h3>
<p>Write a Rack middleware that throws a 404 page displaying "Not OK!" whenever the client tries to access the app using the wrong path. For example, if the client types the URL <a href="http://localhost:9292">http://localhost:9292</a> then the app throws a page displaying "OK!" whereas for any other URL like <a href="http://localhost:9292/newroute">http://localhost:9292/newroute</a> the app throws a 404 page displaying "Not OK!"</p>
<h3>Using Lobster</h3>
<p>Rack comes with little funny web application called "Lobster", that can be used as a demo.</p>
<p>Let us create a <code>config.ru</code> file that contains the following:</p>
<pre># config.ru
require 'rack/lobster'
run Rack::Lobster.new
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, open a command window and type:</p>
<pre>$ rackup config.ru
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a>. You will see a lobster drawing!</p>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<p>The following is credited to <a href="https://github.com/mattetti">Matt Aimonetti</a></p>
<p>Previously we wrote a program <code>my_middleware.rb</code>. We can use this with lobster:</p>
<p>Let us create a <code>config.ru</code> file that contains the following:</p>
<pre># config.ru
require 'rack/lobster'
use MyMiddleware::Hello
run Rack::Lobster.new
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, open a command window and type:</p>
<pre>$ rackup config.ru
</pre>
<p>After you have finished executing this program, press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server. Close the command window.</p>
<h2>Rack::Builder</h2>
<p>Under the hood, <code>rackup</code> converts your <code>config.ru</code> script to an instance of <a href="http://rack.rubyforge.org/doc/classes/Rack/Builder.html">Rack::Builder</a>.</p>
<p><code>Rack::Builder</code> is the thing that glues various Rack middlewares and applications together and converts them into a single entity/rack application. A good analogy is comparing <code>Rack::Builder</code> object with a stack, where at the very bottom is your actual rack application and all middlewares on top of it, and the whole stack itself is a rack application too.</p>
<p>Let us create a <code>config.ru</code> file that contains the following:</p>
<pre>rack_time = Proc.new { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
Rack::Handler::WEBrick.run rack_time, :Port => 9292
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, type:</p>
<pre>rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello. The time is 2011-12-06 11:19:49 +0530
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server.</p>
<p>In <code>config.ru</code>, let us convert <code>rack_time</code> to use <code>Rack::Builder</code>. We will use the block form of <code>Rack::Builder</code>:</p>
<pre>rack_time = Proc.new { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
builder = Rack::Builder.new do
run rack_time
end
Rack::Handler::WEBrick.run builder, :Port => 9292
</pre>
<p><code>Rack::Builder#run</code> specifies the actual rack application you're wrapping with <code>Rack::Builder</code>.</p>
<p>Here <code>Rack::Builder#initialize</code> accepts a block argument, which is evaluated within the context of the newly created instance using <code>instance_eval</code>.</p>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, type:</p>
<pre>rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello. The time is 2011-12-06 11:19:49 +0530
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server.</p>
<p><code>Rack::Builder#use</code> adds a middleware to the rack application stack created by <code>Rack::Builder</code>. Rack has many useful middlewares and one of them is <code>Rack::CommonLogger</code>, which logs a single line to the supplied log file in the Apache common log format.</p>
<p>Let's add <code>Rack::CommonLogger</code> to <code>rack_time</code>:</p>
<pre>require 'logger'
rack_time = Proc.new { |env| [200, {"Content-Type" => "text/plain"}, ["Hello. The time is #{Time.now}"]] }
builder = Rack::Builder.new do
use Rack::CommonLogger
Logger.new('rack.log')
run rack_time
end
Rack::Handler::WEBrick.run builder, :Port => 9292
</pre>
<p>We create an explicit logger <code>rack.log</code>. This log file is created in the same folder as <code>config.ru</code> and contains:</p>
<pre># Logfile created on 2011-12-06 13:54:42 +0530 by logger.rb/31641
</pre>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, type:</p>
<pre>rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>Hello. The time is 2011-12-06 11:19:49 +0530
</pre>
<p>Press <b>Ctrl-C</b> in the command window to stop the <b>WEBrick</b> server.</p>
<p>Let's see how to use <code>Rack::Builder#map</code> to map urls to given actions. Let us create a <code>config.ru</code> file that contains the following:</p>
<pre>require 'logger'
rack_app = Rack::Builder.new do
use Rack::CommonLogger
Logger.new('rack.log')
map "/" do
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["This is public page"]] }
end
map "/secret" do
use Rack::Auth::Basic, "Restricted Area" do |user, password|
user == 'super' && password == 'secretsauce'
end
map "/" do
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["This is a secret page"]] }
end
map "/files" do
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["Here are the secret files"]] }
end
end
end
Rack::Handler::WEBrick.run rack_app, :Port => 9292
</pre>
<p>When you nest map blocks, you'll need to specify URI relative to the enclosing mapping block, as you can clearly see in the example above. We use HTTP Basic Authentication for securing things.</p>
<p>To run our rack app, in the same folder that contains <code>config.ru</code>, type:</p>
<pre>rackup config.ru
[2011-10-25 06:18:16] INFO WEBrick 1.3.1
[2011-10-25 06:18:16] INFO ruby 1.9.3 (2011-07-09) [i386-mingw32]
[2011-10-25 06:18:16] INFO WEBrick::HTTPServer#start: pid=2224 port=9292
</pre>
<p>Open a browser window and type the url: <a href="http://localhost:9292/">http://localhost:9292/</a></p>
<p>In your browser window, you should see something like this:</p>
<pre>This is public page
</pre>
<p>If you type the url: <a href="http://localhost:9292/secret">http://localhost:9292/secret</a></p>
<p>In your browser window, you should see something like this:</p>
<div style="font-size:80%; text-align:center;"><img src="images/auth.jpg" alt="HTTP Basic Authentication" style="padding-bottom:0.5em;" /><br />HTTP Basic Authentication</div>
<p>For User Name type super and for Password type secretsauce. Press the OK button. In your browser window, you should see something like this:</p>
<pre>This is a secret page
</pre>
<p>Now, if you type the url: <a href="http://localhost:9292/secret/files">http://localhost:9292/secret/files</a>, in your browser window, you should see something like this:</p>
<pre>Here are the secret files
</pre>
<p>Do run all the examples in this Rack tutorial, to get a solid understanding of Rack.</p>
<h2>More on Rack</h2>
<p>Pick some projects from <a href="http://coderack.org/">http://coderack.org/</a> and examine the source. You will learn a lot.</p>
<p>
<strong>
<a href="chapter4.html"><Chapter 4 | </a>
<a href="toc.html">TOC | </a>
<a href="chapter6.html">Chapter 6></a>
</strong>
</p>
<div id="footer">
<p>© 2006-2012 <strong>RubyLearning.org - Programming for the Web with Ruby</strong> Page Updated: 27th Jan. 2012</p>
</div>
</div>
</body>
</html>