This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
action_view_overview.html
1828 lines (1664 loc) · 81 KB
/
action_view_overview.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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Action View Overview</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Action View Overview</h2>
<p>In this guide you will learn:</p>
<ul>
<li>What Action View is, and how to use it with Rails</li>
<li>How to use Action View outside of Rails</li>
<li>How best to use templates, partials, and layouts</li>
<li>What helpers are provided by Action View, and how to make your own</li>
<li>How to use localized views</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-action-view">What is Action View?</a></li><li><a href="#using-action-view-with-rails">Using Action View with Rails</a></li><li><a href="#using-action-view-outside-of-rails">Using Action View outside of Rails</a></li><li><a href="#templates-partials-and-layouts">Templates, Partials and Layouts</a></li><li><a href="#using-templates-partials-and-layouts-in-the-rails-way">Using Templates, Partials and Layouts in “The Rails Way”</a></li><li><a href="#partial-layouts">Partial Layouts</a></li><li><a href="#view-paths">View Paths</a></li><li><a href="#overview-of-all-the-helpers-provided-by-action-view">Overview of all the helpers provided by Action View</a><ul><li><a href="#activerecordhelper">ActiveRecordHelper</a></li> <li><a href="#assettaghelper">AssetTagHelper</a></li> <li><a href="#atomfeedhelper">AtomFeedHelper</a></li> <li><a href="#benchmarkhelper">BenchmarkHelper</a></li> <li><a href="#cachehelper">CacheHelper</a></li> <li><a href="#capturehelper">CaptureHelper</a></li> <li><a href="#datehelper">DateHelper</a></li> <li><a href="#debughelper">DebugHelper</a></li> <li><a href="#formhelper">FormHelper</a></li> <li><a href="#formoptionshelper">FormOptionsHelper</a></li> <li><a href="#formtaghelper">FormTagHelper</a></li> <li><a href="#javascripthelper">JavaScriptHelper</a></li> <li><a href="#numberhelper">NumberHelper</a></li> <li><a href="#prototypehelper">PrototypeHelper</a></li> <li><a href="#prototypehelper-javascriptgenerator-generatormethods">PrototypeHelper::JavaScriptGenerator::GeneratorMethods</a></li></ul></li><li><a href="#localized-views">Localized Views</a></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-action-view">1 What is Action View?</h3>
<p>Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing <span class="caps">CRUD</span> actions where necessary. Action View is then responsible for compiling the response.</p>
<p>Action View templates are written using embedded Ruby in tags mingled with <span class="caps">HTML</span>. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It’s also easy to add new helpers to your application as it evolves.</p>
<p>Note: Some features of Action View are tied to Active Record, but that doesn’t mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.</p>
<h3 id="using-action-view-with-rails">2 Using Action View with Rails</h3>
<p><span class="caps">TODO</span>…</p>
<h3 id="using-action-view-outside-of-rails">3 Using Action View outside of Rails</h3>
<p>Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small <a href="http://rack.rubyforge.org/">Rack</a> application that includes Action View functionality. This may be useful, for example, if you’d like access to Action View’s helpers in a Rack application.</p>
<p>Let’s start by ensuring that you have the Action Pack and Rack gems installed:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
gem install actionpack
gem install rack
</pre>
</div>
</notextile>
<p>Now we’ll create a simple “Hello World” application that uses the <tt>titleize</tt> method provided by Active Support.</p>
<p><strong>hello_world.rb:</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'rubygems'
require 'active_support/core_ext/string/inflections'
require 'rack'
def hello_world(env)
[200, {"Content-Type" => "text/html"}, "hello world".titleize]
end
Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
</pre>
</div>
</notextile>
<p>We can see this all come together by starting up the application and then visiting <tt>http://localhost:4567/</tt></p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
ruby hello_world.rb
</pre>
</div>
</notextile>
<p><span class="caps">TODO</span> needs a screenshot? I have one – not sure where to put it.</p>
<p>Notice how ‘hello world’ has been converted into ‘Hello World’ by the <tt>titleize</tt> helper method.</p>
<p>Action View can also be used with <a href="http://www.sinatrarb.com/">Sinatra</a> in the same way.</p>
<p>Let’s start by ensuring that you have the Action Pack and Sinatra gems installed:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
gem install actionpack
gem install sinatra
</pre>
</div>
</notextile>
<p>Now we’ll create the same “Hello World” application in Sinatra.</p>
<p><strong>hello_world.rb:</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'rubygems'
require 'action_view'
require 'sinatra'
get '/' do
erb 'hello world'.titleize
end
</pre>
</div>
</notextile>
<p>Then, we can run the application:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
ruby hello_world.rb
</pre>
</div>
</notextile>
<p>Once the application is running, you can see Sinatra and Action View working together by visiting <tt>http://localhost:4567/</tt></p>
<p><span class="caps">TODO</span> needs a screenshot? I have one – not sure where to put it.</p>
<h3 id="templates-partials-and-layouts">4 Templates, Partials and Layouts</h3>
<p><span class="caps">TODO</span>…</p>
<p><span class="caps">TODO</span> see http://guides.rubyonrails.org/layouts_and_rendering.html</p>
<h3 id="using-templates-partials-and-layouts-in-the-rails-way">5 Using Templates, Partials and Layouts in “The Rails Way”</h3>
<p><span class="caps">TODO</span>…</p>
<h3 id="partial-layouts">6 Partial Layouts</h3>
<p>Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.</p>
<p>Let’s say we’re displaying a post on a page where it should be wrapped in a <tt>div</tt> for display purposes. First, we’ll create a new <tt>Post</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Post.create(:body => 'Partial Layouts are cool!')
</pre>
</div>
</notextile>
<p>In the <tt>show</tt> template, we’ll render the <tt>post</tt> partial wrapped in the <tt>box</tt> layout:</p>
<p><strong>posts/show.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %>
</pre>
</div>
</notextile>
<p>The <tt>box</tt> layout simply wraps the <tt>post</tt> partial in a <tt>div</tt>:</p>
<p><strong>posts/_box.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<div class='box'>
<%= yield %>
</div>
</pre>
</div>
</notextile>
<p>The <tt>post</tt> partial wraps the post’s <tt>body</tt> in a <tt>div</tt> with the <tt>id</tt> of the post using the <tt>div_for</tt> helper:</p>
<p><strong>posts/_post.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<%= div_for(post) do %>
<p><%= post.body %></p>
<% end %>
</pre>
</div>
</notextile>
<p>This example would output the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<div class='box'>
<div id='post_1'>
<p>Partial Layouts are cool!</p>
</div>
</div>
</pre>
</div>
</notextile>
<p>Note that the partial layout has access to the local <tt>post</tt> variable that was passed into the <tt>render</tt> call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.</p>
<p>You can also render a block of code within a partial layout instead of calling <tt>yield</tt>. For example, if we didn’t have the <tt>post</tt> partial, we could do this instead:</p>
<p><strong>posts/show.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% render(:layout => 'box', :locals => {:post => @post}) do %>
<%= div_for(post) do %>
<p><%= post.body %></p>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>If we’re using the same <tt>box</tt> partial from above, his would produce the same output as the previous example.</p>
<h3 id="view-paths">7 View Paths</h3>
<p><span class="caps">TODO</span>…</p>
<h3 id="overview-of-all-the-helpers-provided-by-action-view">8 Overview of all the helpers provided by Action View</h3>
<p>The following is only a brief overview summary of the helpers available in Action View. It’s recommended that you review the <span class="caps">API</span> Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.</p>
<h4 id="activerecordhelper">8.1 ActiveRecordHelper</h4>
<p>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the <a href="form_helpers.html">Rails Form helpers guide</a>.</p>
<h5 id="error_message_on">8.1.1 error_message_on</h5>
<p>Returns a string containing the error message attached to the method on the object if one exists.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
error_message_on "post", "title"
</pre>
</div>
</notextile>
<h5 id="error_messages_for">8.1.2 error_messages_for</h5>
<p>Returns a string with a <span class="caps">DIV</span> containing all of the error messages for the objects located as instance variables by the names given.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
error_messages_for "post"
</pre>
</div>
</notextile>
<h5 id="form">8.1.3 form</h5>
<p>Returns a form with inputs for all attributes of the specified Active Record object. For example, let’s say we have a <tt>@post</tt> with attributes named <tt>title</tt> of type <tt>String</tt> and <tt>body</tt> of type <tt>Text</tt>. Calling <tt>form</tt> would produce a form to creating a new post with inputs for those attributes.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form("post")
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action='/posts/create' method='post'>
<p>
<label for="post_title">Title</label><br />
<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
</p>
<p>
<label for="post_body">Body</label><br />
<textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
</p>
<input name="commit" type="submit" value="Create" />
</form>
</pre>
</div>
</notextile>
<p>Typically, <tt>form_for</tt> is used instead of <tt>form</tt> because it doesn’t automatically include all of the model’s attributes.</p>
<h5 id="input">8.1.4 input</h5>
<p>Returns a default input tag for the type of object returned by the method.</p>
<p>For example, if <tt>@post</tt> has an attribute <tt>title</tt> mapped to a <tt>String</tt> column that holds “Hello World”:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
input("post", "title") # =>
<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
</pre>
</div>
</notextile>
<h4 id="assettaghelper">8.2 AssetTagHelper</h4>
<p>This module provides methods for generating <span class="caps">HTML</span> that links views to assets such as images, JavaScript files, stylesheets, and feeds.</p>
<p>By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting <tt>ActionController::Base.asset_host</tt> in the application configuration, typically in <tt>config/environments/production.rb</tt>. For example, let’s say your asset host is <tt>assets.example.com</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
</pre>
</div>
</notextile>
<h5 id="register_javascript_expansion">8.2.1 register_javascript_expansion</h5>
<p>Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in <tt>public/javascripts</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/head.js"></script>
<script type="text/javascript" src="/javascripts/body.js"></script>
<script type="text/javascript" src="/javascripts/tail.js"></script>
</pre>
</div>
</notextile>
<h5 id="register_stylesheet_expansion">8.2.2 register_stylesheet_expansion</h5>
<p>Register one or more stylesheet files to be included when symbol is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in <tt>public/stylesheets</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
<link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
</pre>
</div>
</notextile>
<h5 id="auto_discovery_link_tag">8.2.3 auto_discovery_link_tag</h5>
<p>Returns a link tag that browsers and news readers can use to auto-detect an <span class="caps">RSS</span> or <span class="caps">ATOM</span> feed.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
</pre>
</div>
</notextile>
<h5 id="image_path">8.2.4 image_path</h5>
<p>Computes the path to an image asset in the <tt>public/images</tt> directory. Full paths from the document root will be passed through. Used internally by <tt>image_tag</tt> to build the image path.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_path("edit.png") # => /images/edit.png
</pre>
</div>
</notextile>
<h5 id="image_tag">8.2.5 image_tag</h5>
<p>Returns an html image tag for the source. The source can be a full path or a file that exists in your <tt>public/images</tt> directory.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
</pre>
</div>
</notextile>
<h5 id="javascript_include_tag">8.2.6 javascript_include_tag</h5>
<p>Returns an html script tag for each of the sources provided. You can pass in the filename (<tt>.js</tt> extension is optional) of JavaScript files that exist in your <tt>public/javascripts</tt> directory for inclusion into the current page or you can pass the full path relative to your document root.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag "common" # =>
<script type="text/javascript" src="/javascripts/common.js"></script>
</pre>
</div>
</notextile>
<p>To include the Prototype and Scriptaculous JavaScript libraries in your application, pass <tt>:defaults</tt> as the source. When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in your <tt>public/javascripts</tt> directory, it will be included as well.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :defaults
</pre>
</div>
</notextile>
<p>You can also include all JavaScript files in the <tt>public/javascripts</tt> directory using <tt>:all</tt> as the source.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :all
</pre>
</div>
</notextile>
<p>You can also cache multiple JavaScript files into one file, which requires less <span class="caps">HTTP</span> connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if <tt>ActionController::Base.perform_caching</tt> is set to true (which is the case by default for the Rails production environment, but not for the development environment).</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :all, :cache => true # =>
<script type="text/javascript" src="/javascripts/all.js"></script>
</pre>
</div>
</notextile>
<h5 id="javascript_path">8.2.7 javascript_path</h5>
<p>Computes the path to a JavaScript asset in the <tt>public/javascripts</tt> directory. If the source filename has no extension, <tt>.js</tt> will be appended. Full paths from the document root will be passed through. Used internally by <tt>javascript_include_tag</tt> to build the script path.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_path "common" # => /javascripts/common.js
</pre>
</div>
</notextile>
<h5 id="stylesheet_link_tag">8.2.8 stylesheet_link_tag</h5>
<p>Returns a stylesheet link tag for the sources specified as arguments. If you don’t specify an extension, <tt>.css</tt> will be appended automatically.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag "application" # =>
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
</pre>
</div>
</notextile>
<p>You can also include all styles in the stylesheet directory using :all as the source:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag :all
</pre>
</div>
</notextile>
<p>You can also cache multiple stylesheets into one file, which requires less <span class="caps">HTTP</span> connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment).</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag :all, :cache => true
<link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
</pre>
</div>
</notextile>
<h5 id="stylesheet_path">8.2.9 stylesheet_path</h5>
<p>Computes the path to a stylesheet asset in the <tt>public/stylesheets</tt> directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_path "application" # => /stylesheets/application.css
</pre>
</div>
</notextile>
<h4 id="atomfeedhelper">8.3 AtomFeedHelper</h4>
<h5 id="atom_feed">8.3.1 atom_feed</h5>
<p>This helper makes building an <span class="caps">ATOM</span> feed easy. Here’s a full usage example:</p>
<p><strong>config/routes.rb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :posts
</pre>
</div>
</notextile>
<p><strong>app/controllers/posts_controller.rb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@posts = Post.all
respond_to do |format|
format.html
format.atom
end
end
</pre>
</div>
</notextile>
<p><strong>app/views/posts/index.atom.builder</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
atom_feed do |feed|
feed.title("Posts Index")
feed.updated((@posts.first.created_at))
for post in @posts
feed.entry(post) do |entry|
entry.title(post.title)
entry.content(post.body, :type => 'html')
entry.author do |author|
author.name(post.author_name)
end
end
end
end
</pre>
</div>
</notextile>
<h4 id="benchmarkhelper">8.4 BenchmarkHelper</h4>
<h5 id="benchmark">8.4.1 benchmark</h5>
<p>Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
</pre>
</div>
</notextile>
<p>This would add something like “Process data files (0.34523)” to the log, which you can then use to compare timings when optimizing your code.</p>
<h4 id="cachehelper">8.5 CacheHelper</h4>
<h5 id="cache">8.5.1 cache</h5>
<p>A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static <span class="caps">HTML</span> fragments, and so on. This method takes a block that contains the content you wish to cache. See <tt>ActionController::Caching::Fragments</tt> for more information.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% cache do %>
<%= render "shared/footer" %>
<% end %>
</pre>
</div>
</notextile>
<h4 id="capturehelper">8.6 CaptureHelper</h4>
<h5 id="capture">8.6.1 capture</h5>
<p>The <tt>capture</tt> method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
</pre>
</div>
</notextile>
<p>The captured variable can then be used anywhere else.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<%= @greeting %>
</body>
</html>
</pre>
</div>
</notextile>
<h5 id="content_for">8.6.2 content_for</h5>
<p>Calling <tt>content_for</tt> stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to <tt>yield</tt>.</p>
<p>For example, let’s say we have a standard application layout, but also a special page that requires certain Javascript that the rest of the site doesn’t need. We can use <tt>content_for</tt> to include this Javascript on our special page without fattening up the rest of the site.</p>
<p><strong>app/views/layouts/application.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
<%= yield :special_script %>
</head>
<body>
<p>Welcome! The date and time is <%= Time.now %></p>
</body>
</html>
</pre>
</div>
</notextile>
<p><strong>app/views/posts/special.html.erb</strong></p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<p>This is a special page.</p>
<% content_for :special_script do %>
<script type="text/javascript">alert('Hello!')</script>
<% end %>
</pre>
</div>
</notextile>
<h4 id="datehelper">8.7 DateHelper</h4>
<h5 id="date_select">8.7.1 date_select</h5>
<p>Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
date_select("post", "published_on")
</pre>
</div>
</notextile>
<h5 id="datetime_select">8.7.2 datetime_select</h5>
<p>Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
datetime_select("post", "published_on")
</pre>
</div>
</notextile>
<h5 id="distance_of_time_in_words">8.7.3 distance_of_time_in_words</h5>
<p>Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set <tt>include_seconds</tt> to true if you want more detailed approximations.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, true) # => less than 20 seconds
</pre>
</div>
</notextile>
<h5 id="select_date">8.7.4 select_date</h5>
<p>Returns a set of html select-tags (one for year, month, and day) pre-selected with the <tt>date</tt> provided.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
select_date()
</pre>
</div>
</notextile>
<h5 id="select_datetime">8.7.5 select_datetime</h5>
<p>Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the <tt>datetime</tt> provided.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()
</pre>
</div>
</notextile>
<h5 id="select_day">8.7.6 select_day</h5>
<p>Returns a select tag with options for each of the days 1 through 31 with the current day selected.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)
# Generates a select field for days that defaults to the number given
select_day(5)
</pre>
</div>
</notextile>
<h5 id="select_hour">8.7.7 select_hour</h5>
<p>Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for minutes that defaults to the minutes for the time provided
select_minute(Time.now + 6.hours)
</pre>
</div>
</notextile>
<h5 id="select_minute">8.7.8 select_minute</h5>
<p>Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
</pre>
</div>
</notextile>
<h5 id="select_month">8.7.9 select_month</h5>
<p>Returns a select tag with options for each of the months January through December with the current month selected.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</pre>
</div>
</notextile>
<h5 id="select_second">8.7.10 select_second</h5>
<p>Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)
</pre>
</div>
</notextile>
<h5 id="select_time">8.7.11 select_time</h5>
<p>Returns a set of html select-tags (one for hour and minute).</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a time select that defaults to the time provided
select_time(Time.now)
</pre>
</div>
</notextile>
<h5 id="select_year">8.7.12 select_year</h5>
<p>Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the <tt>options</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for five years on either side of +Date.today+ that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, :start_year => 1900, :end_year => 2009)
</pre>
</div>
</notextile>
<h5 id="time_ago_in_words">8.7.13 time_ago_in_words</h5>
<p>Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
time_ago_in_words(3.minutes.from_now) # => 3 minutes
</pre>
</div>
</notextile>
<h5 id="time_select">8.7.14 time_select</h5>
<p>Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
</pre>
</div>
</notextile>
<h4 id="debughelper">8.8 DebugHelper</h4>
<p>Returns a <tt>pre</tt> tag that has object dumped by <span class="caps">YAML</span>. This creates a very readable way to inspect an object.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
debug(my_hash)
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
</pre>
</div>
</notextile>
<h4 id="formhelper">8.9 FormHelper</h4>
<p>Form helpers are designed to make working with models much easier compared to using just standard <span class="caps">HTML</span> elements by providing a set of methods for creating forms based on your models. This helper generates the <span class="caps">HTML</span> for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.</p>
<p>There are two types of form helpers: those that specifically work with model attributes and those that don’t. This helper deals with those that work with model attributes; to see an example of form helpers that don‘t work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.</p>
<p>The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let’s say that you have a model Person and want to create a new instance of it:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, :url => { :action => "create" } do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
<% end %>
</pre>
</div>
</notextile>
<p>The <span class="caps">HTML</span> generated for this would be:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action="/persons/create" method="post">
<input id="person_first_name" name="person[first_name]" size="30" type="text" />
<input id="person_last_name" name="person[last_name]" size="30" type="text" />
<input name="commit" type="submit" value="Create" />
</form>
</pre>
</div>
</notextile>
<p>The params object created when this form is submitted would look like:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
</pre>
</div>
</notextile>
<p>The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.</p>
<h5 id="check_box">8.9.1 check_box</h5>
<p>Returns a checkbox tag tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @post.validated? is 1:
check_box("post", "validated")
# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
# <input name="post[validated]" type="hidden" value="0" />
</pre>
</div>
</notextile>
<h5 id="fields_for">8.9.2 fields_for</h5>
<p>Creates a scope around a specific model object like form_for, but doesn‘t create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<%= form_for @person, :url => { :action => "update" } do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<h5 id="file_field">8.9.3 file_field</h5>
<p>Returns an file upload input tag tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
</pre>
</div>
</notextile>
<h5 id="form_for">8.9.4 form_for</h5>
<p>Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<%= form_for @post do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %><br />
<%= f.label :body, 'Body' %>:
<%= f.text_area :body %><br />
<% end %>
</pre>
</div>
</notextile>
<h5 id="hidden_field">8.9.5 hidden_field</h5>
<p>Returns a hidden input tag tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
</pre>
</div>
</notextile>
<h5 id="label">8.9.6 label</h5>
<p>Returns a label tag tailored for labelling an input field for a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
label(:post, :title)
# => <label for="post_title">Title</label>
</pre>
</div>
</notextile>
<h5 id="password_field">8.9.7 password_field</h5>
<p>Returns an input tag of the “password” type tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
</pre>
</div>
</notextile>
<h5 id="radio_button">8.9.8 radio_button</h5>
<p>Returns a radio button tag for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @post.category returns "rails":
radio_button("post", "category", "rails")
radio_button("post", "category", "java")
# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
# <input type="radio" id="post_category_java" name="post[category]" value="java" />
</pre>
</div>
</notextile>
<h5 id="text_area">8.9.9 text_area</h5>
<p>Returns a textarea opening and closing tag set tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
text_area(:comment, :text, :size => "20x30")
# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
# #{@comment.text}
# </textarea>
</pre>
</div>
</notextile>
<h5 id="text_field">8.9.10 text_field</h5>
<p>Returns an input tag of the “text” type tailored for accessing a specified attribute.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
text_field(:post, :title)
# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
</pre>